Thursday, November 3, 2011

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

Recently I built a website like, which allocates each user an unique URL for his profile page. Therefore, URL rewriting is needed. For example, should be rewritten to be 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/ Note the path for 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 to And the last line redirects to

Test it out
Now when you type into your browser, the content of will be returned though user can only see in his browser address bar.

No comments:

Post a Comment