mod rewrite

Posted under » Apache on 23 April 2010

First is to test if mod rewrite is indeed working. In this example, any request for tony.html will be directed to bob.html.

Take note, "RewriteEngine on" must always be there first.

RewriteEngine on
RewriteRule ^tony.html$ bob.html

I don't actually understand how this thing work. What I want to do is to redirect the site root to a sub folder because I can't change the config file.

In this case I have to put the script on .htaccess. Please ensure that the particular folder has "AllowOverride All" in the Apache config.

.htaccess file made from windows will not work since .htaccess is not a windows thing.

RewriteEngine On

RewriteCond %{HTTP_HOST} ^(www\.)?yoursite\.com$ [NC]
RewriteCond %{DOCUMENT_ROOT}/blogsite%{REQUEST_URI}/ -d
RewriteRule [^/]$ %{REQUEST_URI}/ [R=301,L]

RewriteCond %{HTTP_HOST} ^(www\.)?yoursite\.com$ [NC]
RewriteRule ^(.*)$ /blogsite/$1 [QSA,L]

Take note and read more of %{server variable}, regex ^(.*)$ and the ones in brackets, [NC].

Now I want to redirect personal user folder to another server. In some OS, you need a backslash. If you notice there is a lot of regex going on in mod-rewrite. This example is easier to understand.

RewriteRule ^/~(.+) http://web.yourside.com/~$1 [R]
RewriteRule ^~(.+) http://web.yourside.com/~$1 [R]

The above is a redirection [R] but if you want a rewrite you use [QSA,L]. like so.

RewriteRule ^~(.+) http://web.yourside.com/~$1 [QSA,L]

Now suppose you have a folder in the root directory that actually contains the contents. You use the RewriteBase. Which is quite similar to the above axample.

RewriteBase   /blogsite
RewriteRule ^old(.*)$ archive$1 [QSA,L]

Redirect numbers to another folder.

# Redirect numb3rs
RewriteRule ^([0-9]+) /php/$1.php [QSA,L]

So. http://www.yourside.com/old/heh.html will actually serve up
http://www.yourside.com/blogsite/archive/heh.html. Notice in this example, rewritebase reduce one folder level.

A think to note is that mod-rewrite is not the real thing. It's a pseudo kind of URL manipulation.

Sorry if this has been brief but here is a way much better mod_rewrite resource page.

From the official documentation.

web security linux ubuntu python django git Raspberry apache mysql php drupal cake javascript css AWS