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

Remove multiple file extensions using RewriteRule in htaccess.

Remove html PHP extension using htaccess

How to remove multiple file extensions using RewriteRule in htaccess ?

.htaccess is a directory level configuration file used on apache server. Many users who don’t have access to their main server.config file use htaccess to rewrite URLs and configure other custom server settings. Htaccess is often used by Apache users to shorten URLs when they want to turn a long and non-memorable URL into short and memorable one. One of the most used rewriteRule on htaccess is “File extension removal” rule. Users find it easier then server.config to RewriteRule through htaccess. In this post I will show you how you can remove any file extension using htaccess.

What you will need:

  • Apache server
  • Mod-rewrite
  • .htaccess support

Apache server

You must have an apache server to use RewriteRules.

Mod-rewrite

Mod-rewrite is a rewrite module provided by apache. You must have this module enabled on your server in order to use RewriteRules directive. Some hosting service providers have enabled it by default but in case its not enabled ,you can enable it by adding one mazic line AllowOverride All in your server.config file. If you don’t have access to this file then ask your hosting service to enable it for you.

.htaccess

.htaccess is where you will write rule code. htaccess is a dot perfix file. If your hosting service hasn’t enabled it then ask them to enable it.

Remove file extension using RewriteRule

With a RewriteRule directive, you can remove the traling .php from your php files. For example You will only type /filename instead of /filename.php . Filenames with extension do not cause any SEO issues but if you remove the extension then appearance of URL becomes awasome. The following is the rule to remove .php extension from urls. You can edit it to remove other extensions accordingly by just replacing .php with your file extension :

RewriteEngine on
#2)
RewriteRule %{THE_REQUEST} /(.*).php [NC]
#2)
RewriteRule (.*) /%1 [L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*)/?$ /$1.php [L]

The rewrite rule above would redirect any php file url ie (foo.php) to remove the extension. The first set of rule redirects /file.php to /file and the second one then internally maps /file to its original location /file.php .

Remove multiple file extensions using RewriteRule in htaccess

It is possible to remove multiple file extensions using two rules. You can capture file extensions using regex in RewriteCond and then rewrite the request accordingly.

RewriteEngine on
RewriteCond %{THE_REQUEST} /([^.]+).(php|html|css) [NC]
RewriteRule ^ /%1 [L,R]
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule (.*)/?$ /$1.php [NC,L]

The simple approach works for any file extension you want to remove.

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 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.

Categories
apache apache restart server htaccess rule

Is restarting apache server required for htaccess rules?

Do I need to restart apache server to use RewriteRules in htaccess?

Restart apace server

New users often ask whether they should restart apache server after making changes in htaccess rules. I see a similar question being asked more and more often on question and answer sites like Stackoverflow. So I decided to write my own post that will give you a clear overview .
In this post I will answer wether you need to restart your server or not with some explanations .

If you do not want to read the entire post or you are just looking for an instant answer, then

The short and simple answer is : NO

You don’t need to restart apache server to use RewriteRules.

Why?

Because webserver reads htaccess each time a file is requested from server.
When you request something from apache web server , your server reads your htaccess file before serving the request and this way your htaccess file is automatically updated.

Since an htaccess file gets updated automatically , you do not need to restart the server. The changes you make in your htaccess files are auto applied when you request an URI. For example: if you add a new rule to redirect your site to non www version, you can simply test your rule by typing your URL in a web browser without needing to restart the server.

What if I am using RewriteRules in a server.config file?

If your rules are in a server.config file then restating the server is required. If you make some changes to your config file and don’t restart the server then those changes wont apply to your server. The main diffrence between htaccess and server.config file is an htaccess gets updated automatically while server.config files updates only once when you restart your server. Your webserver remembers the contents of server.config untill you manually restart it.

So finally, you must restart your apache web server after making changes in your server config file. But if you are using htaccess then you can simply save the code and type your URL to test your new rules.