Thursday, November 3, 2011

Apache (PHP) URL rewrite using mod_rewrite (URL 重写)

Recently I built a website like about.me, which allocates each user an unique URL for his profile page. Therefore, URL rewriting is needed. For example, http://mysite.com/myusername/ should be rewritten to be http://mysite.com/profile.php?username=myusername. The purpose here is making the URL seen by the end-user prettier as well as hiding the real filename (i.e., profile.php). More detailed advantage of URL rewriting can be found here. There are a bunch of examples and blogs showing how to make this happen. However, to make it simple and quick, only an example with minimal setup is given below.

Make sure that mod_rewrite module is loaded in apache server:
Open your httpd.conf file (usually locates in /etc/apache2/ on Linux). Add the following line to httpd.conf if it doesn't exists: LoadModule rewrite_module /usr/lib/apache2/modules/mod_rewrite.so. Note the path for mode_rewrite.so may be different on your server. For more information about mod_rewrite, click here.

Enable FollowSymLinks option:
FollowSymLinks can be enabled on the whole server by adding the following line in httpd.conf: Options FollowSymLinks. It can also be enabled for a specific directory by adding Options +FollowSymLinks in the file .htaccess, which locates in that directory. For more information on FollowSymLinks, a good blog of FollowSymLinks can be found here.

Add rewrite rules into .htaccess
Create a .htaccess file in the directory where you want URL rewrite happens. Add the following two lines:
RewriteEngine on
RewriteRule ^/?([a-zA-Z0-9]+)/$ /$1 [R]
RewriteRule ^/?([a-zA-Z0-9]+)$ /profile.php?username=$1

The first line enables mod_rewrite. The second line redirects http request mysite.com/username/ to mysite.com/username. And the last line redirects mysite.com/username to mysite.com/profile.php?username=username.

Test it out
Now when you type mysite.com/xxx/ into your browser, the content of mysite.com/profile.php?username=xxx will be returned though user can only see mysite.com/xxx/ in his browser address bar.

No comments:

Post a Comment