Categories
Apache mod-rewrite and htaccess related Articles htaccess moder rewrite rules

5 awesome htaccess copy and paste Rewrite rules with explanations

htaccess RewriteRules

I often see people struggling with their mod-rewrite code and when they think they can’t fix the issue themselves, they either go to stackoverflow or keep scrolling the search results and hopefully ,perhaps get the solution there.

URL rewriting is not as complicated as new users find it. Like other languages, URL rewriting is a mazic of syntex. If you are learning from the scratch then learning its basic syntex first can help you better understand it and speed up your learning skill.

There are alot of learning resources on the Internet including the official mod-rewrite guide where you can start.

In this post, I am going to share 5 apache RewriteRule scripts that you can easily copy and paste to your server.config or htaccess
file to use them.

#1) Rewriting a long url to make it short and search engine friendly

With apache mod-rewrite, you can turn a longer looking URL into short one.
Let’s assume you have long URL with query variables which looks something like the following:
http://example.com/users.php?user=foo

The one main problem with the URL above is that it is longer, not memorable and non-SEF . Search engines often ignore such URLs due to the duplicate URL issues.

To make the above URL short and SEF , you can use RewriteRule in your server.config or htaccess file.
With a RewriteRule you can turn the URL into the following format:

http://example.com/users/foo

The URL looks awasome now. Doesn’t it?

RewriteRule script :
RewriteRule ^users/(.+)$ /users.php?user=$1 [L]

You can simply copy and paste the rule above to your htaccess or server.config file and put it bellow “RewriteEngine On” .

#2 Setting an environment variable using RewriteRule

You can set a URI based environment variable on your server using RewriteRule directive. Settings the variable via RewriteRule is easier then setting it in php. You can set an environment variable for specific URIs when these URIs pass through the RewriteRule.
The following RewriteRule code example sets an environment variable named foo and value bar for file.php meaning that when you request the /file.php the rule will automatically set the variable. You can copy the code from textarea bellow and put it in your htaccess file.

RewriteRule script :
RewriteRule ^file.php$ - [E=foo:bar]

#3) Access files without extensions

A simple one liner code to ignore file extensions on Apache server. If you want to access your files without typing extensions at the end, for example to
access file.html as file you can use the following line in your htaccess file :

Options +Multiviews

#4) non-www to www URL redirection

RewriteRules can be used to redirect a non-www (naked domain) to its www version. To redirect your non-www URLs to www , you can use the rule bellow:
RewriteEngine on
RewriteCond %{HTTP_HOST} !www. [NC]
RewriteRule (.*) http://www.example.com%{REQUEST_URI} [R=301,L]

We use RewriteCond (condition) directive to test the host header string. If the test string %{HTTP_HOST} matches the pattern !^www then the rule is applied.. In simple words, if you type yourdomain.com into your browser the rule will redirect it to www.example.com .

#5) Custom 404 rule

With mod rewrite you can create a custom 404 rule for your website. You can redirect your visitors to a specific page on your site when they request a broken or not-found link.

The following RewriteRule script rewrites 404 requests to /file.php on your server. If you are using wordpress, add this before the WordPress default rule .

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*) http://www.example.com%{REQUEST_URI} [R=301,L]

Categories
apache Seo

Should you htaccess or server.config file on apache server?

htaccess vs server.config . Which one should be used

Should you use htaccess or server.config file?

This is a common question among many apache mod-rewrite users especially among newbies as they are curious about it.
If you search this topic on google you will get hundreds of top results where experts advice you not to use htaccess.
One true answer to the question can be found on official apache mod-rewrite manual https://httpd.apache.org/docs/2.4/howto/htaccess.html .

Screenshot from the official apache mod-rewrite manual:

htaccess vs server.config file apache

What is a server.config file?

It is a server level config file located in your httpd server root. You can put directives in this file to customize the behaviour of your server.

What is an htaccess file?

htaccess is a directory leve config file located in your document root.
By directory level I mean to say that you can use it in your main directory if you want the htaccess to effect the folder and its subfolders or you can also use it in a particular folder/subfolder so that it can affect the folder accordingly.

Not all hosting providers allow you to access server.config

Some paid or free webhosting providers do not allow you to edit server.config on their server that means that you only have access to a dynamic configuration file called .htaccess.
htaccess file can be placed anywhere in any directory .
Even wordpress installation contains an htaccess file to create short and friendly URLs.
But the question “Should I use htaccess or server.config file ” still keeps popping up in our mind and everyone seems to be curious to know it.

server.config or htaccess?

If you do not have access to the main config file on your server then You can use htaccess. There is nothing wrong with using an htaccess file. You won’t lose your seo rank. But there are some performance issues that can effect your site.
Apache mod rewrite documentation says that “htaccess file slows down the performance of a webserver” . Yes it does..but very little 0.5 or 1%. You can’t even notice how much your server performance and page load speed is affected.
So you don’t have be worried about it.
The difference between a server.config and an htaccess file is that you a server.config file supports all directives while an htaccess doesn’t like RewriteMap and there are some other useful directives that you cant use in an htaccess file.

Another big diffrence between these contexts is how a web server reads/executives these files. A server.config file is read by server only once. A htaccess file is read on each request. When you request sa file or directory from webserver , your webserver first reads the htaccess to serve you the file dir according to commands you put in htaccess. Server.config file on the on other is read only onec you update it.

To better understand how an htaccess file can slow down your webserver, consider the following example :

Say you an htaccess file in your directory to rewrite “/file.php” to “/file2.php” .

You type “/file.php” in your browser address bar.

You webserver receive the request “/file.php” .
In order to serve you the “/file2.php” your server reads your htaccess two times.
1) Your server reads your htaccess contents and rewrites “/file.php” to “/file2.php” .
2) Your server again reads your htaccess file to serve you the destination file “/file2.php” .
As you can see your webserver read your htaccess two times to serve a simple request. Then obviously your page load speed will degrees by 1 or 2% .

Categories
Apache mod-rewrite and htaccess related Articles

Most commonly used flags in RewriteRule | mod_rewrite flags

Flags are optional in mod_rewrite. They are used to change behaviour of RewriteRule directive. A RewriteRule can have at least one or multiple flags separated by a comma , character.
In RewriteRule flags are used inside sequere brackets [] .
The basic use of flags in RewriteRule is to instruct the engine how the rule should handle an http request. For example a rule with NC flag tells the engine to ignore URI character case so both Uppercase and Lowercase URIs are accepted by RewriteRule instead of just accepting lowercase URI which is the default behaviour.

This article covers all the most commonly used flags in RewriteRule with code examples and explainations on how they work.

Table of contents (Most used flags in RewriteRule)

[L] flag in RewriteRule

L stands for Last . We use L flag in RewriteRule to tell server that the rule is last. L flag gives instruction to server not to execute other rules if the specific one matches.

Forexample : If you have the following two rules in .htaccess file :

RewriteRule ^this /thispath
RewriteRule ^this /secondpath

As you can see the flag is ommited in rules above , so a request for /this will serve you the secondpath instead of the first rule’s destination path.
L flag is especially desigined to solve this type of rule’s confliction.

[NC] flag in RewriteRule

NC stands for NoCase . As the name states, this flag is used to match an URI in a case-insenstive manner meaning that your URI can contain both uppercase and lowercase URI characters.
The following is an example of NC flag in a RewriteRule :

RewriteRule ^hello$ /file.php [NC]

As you can we used NC in the rule above. With NC the Rule above will accept both URIs /hello and /HeLLo as the Case is ignored by NC flag.

[R] flag in RewriteRule

R stands for
Redirect . We use R flag in RewriteRule to redirect an URI from one location to the other. By default R redirects an URI using 302 redirect status which is temporary Redirect. You can manully append Redirect status code to R flag to change the redirect status ie: R=301 , R=403 etc.

See the rule example bellow to better understand how it works:

RewriteRule ^thisPath$ /thatPath [R=301]

The rewriteRule above will redirect /thisPath to /thatPath using the HTTP redirect status 301 changing the browser URL from old to new.

[QSA] flag in RewriteRule

QSA stands for
QueryStringAppend .
We use QSA in RewriteRule directive to combine new and old querystrings for example /this?q=bar to /that?query1=foo . QSA flag appends the old querystring to new target path like so /that?query=foo&q=bar.
You must use QSA in a RewriteRule when the target path of your rewriteRule already contains a querystring and you want to pass additional query perameters via your new URL to the old one.
The Rule example bellow will help you better understand the importance of QSA :

RewriteRule ^this.php$ /that.php?page=2 [QSA]

The rule above does two things, it rewrites /this.php to /that.php?page=2 and it will also pass additional query strings from your new URL path to the target path

forexample: /this.php?lang=en will also successfully map to /that.php?page=2&lang=en.

But if you remove the QSA then you wont get the same behaviour. Without QSA flag the additional query perameters you pass will get descarded.

[NE] flag in RewriteRule

NE | NoEscape flag tells apache not to convert special URI chracters like # , ? .. to their hex code. On apache server by default theses characters get changed ie # becomes %23 which can cause a not found url error on your server. See the example bellow we are using to redirect to a fregment path.

RewriteRule ^this$ /that#a [R,NE]

With NE flag the rule will redirect a request for /this$ to /that#a . If the NE is ommited then the URL you will land on would look something like /that%23a which is an invalid path.

[P] proxy flag in RewriteRule

P stands for Proxy . This flag is use in RewriteRule to proxy requests between two domains or two two different http hosts.
With P flag it is possible to rewrite your domain name to another domain without changing the URL in browser address bar.
To use P flag , first you must enable Proxy module on your Apache web server otherwise you will get a 500 “internal server error” .
The following is an example of P flag in a RewriteRule .

RewriteEngine on
RewriteRule (.*) https://example.com [P]

This will internally map all requests from your domain to example.com domain.

For example , a request for https://yoursite.com/* will get served from https://example.com without the URL change.