URL rewriting is a technique that transforms complex URLs into simple and readable formats, helping to improve user experience and SEO rankings. For example, converting the URL "http://example.com/index.php?page=about" to "http://example.com/about" not only simplifies the user access path but also makes it easier for search engines to index.
In the process of PHP URL rewriting, you first need to ensure that the mod_rewrite module is installed and enabled on your Apache server. On Linux systems, you can verify this by running the following command:
$ apache2ctl -M | grep rewrite_module
If the output contains "rewrite_module", it means the module is enabled. Next, open the Apache configuration file (e.g., httpd.conf or apache2.conf) and make sure the following line is not commented out:
LoadModule rewrite_module modules/mod_rewrite.so
After making the necessary changes, restart the Apache server to apply the configuration.
The .htaccess file, located in the root directory of the website, can be used to configure the behavior of the Apache server. To enable URL rewriting, the RewriteEngine directive should be added in the .htaccess file. Create a new text file and add the following content:
RewriteEngine On
URL rewriting rules specify how URLs are transformed. In the .htaccess file, we use the RewriteRule directive to define these rules. Here's a simple rule example:
RewriteEngine On
RewriteRule ^about$ index.php?page=about [L]
This rule will rewrite "http://example.com/about" to "http://example.com/index.php?page=about", and the [ L ] flag indicates that no further rules should be applied if a match is found.
In addition to simple URL transformation, URL rewriting can also implement several advanced features, such as removing file extensions, pagination, and beautifying URLs. Below are some common use cases:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ $1.php [NC,L]
This rule will rewrite "http://example.com/about.php" to "http://example.com/about", removing the .php extension.
RewriteEngine On
RewriteRule ^page/([0-9]+)$ index.php?page=$1 [NC,L]
This rule will rewrite "http://example.com/page/2" to "http://example.com/index.php?page=2", enabling pagination through the URL.
RewriteEngine On
RewriteRule ^product/([0-9]+)/([a-zA-Z0-9-]+)$ product.php?id=$1&name=$2 [NC,L]
This rule will rewrite "http://example.com/product/1/iphone" to "http://example.com/product.php?id=1&name=iphone", achieving a more user-friendly URL for product pages.
This article introduced how to use URL rewriting in PHP. By configuring the mod_rewrite module in Apache and editing the .htaccess file, you can simplify your website's URLs, making them more user-friendly and SEO-optimized. We also provided common examples of URL rewriting to help you enhance your web development process.