Redirecting URLs in Apache for PHP with .htaccess and mod_rewrite
Last update: 07-03-2024
If you're working with a PHP application hosted on an Apache server and need to redirect URLs like
domain/item/{param}
(such as
domain/item/1
, domain/item/2
, and so on) to
domain/item
this guide will walk you through the necessary steps. We'll cover how to configure your .htaccess file and make changes to your virtual host file to achieve this. This approach is particularly useful for supporting path parameters and query parameters in PHP applications when you are using pure PHP without a framework.
Step 1: Create and Configure Your .htaccess File
The .htaccess file allows you to define rules for URL rewriting and other directives. To redirect URLs in the format domain/item/{param}
to domain/item
, follow these steps:
- Navigate to the root folder of your website.
- Create a new .htaccess file if it doesn't already exist.
- Add the following lines to your .htaccess file:
RewriteEngine On RewriteRule ^item/(.*)$ item.php?name=$1 [L,QSA]
This configuration tells Apache to redirect any URL starting with item/
to item.php
, converting the path into a query parameter with the key name
. For example, the original URL:
domain/item/1?foo=bar
will be rewritten as
domain/item.php?name=1&foo=bar
with the original path appended as a query parameter.
Step 2: Edit the Virtual Host File
The virtual host file, by default named 000-default.conf
, defines the settings for your website. To ensure that Apache processes your .htaccess file, you'll need to modify this file as follows:
- Open the virtual host file in a text editor:
sudo nano /etc/apache2/sites-available/000-default.conf
- Add the following configuration inside the
<VirtualHost>
block:
Options Indexes FollowSymLinks AllowOverride All Require all granted
This directive allows Apache to follow symbolic links and use the settings defined in your .htaccess file. The Require all granted
directive ensures that all requests are allowed.
Step 3: Enable the mod_rewrite Module
Apache's mod_rewrite
module is required for the rewrite rules to work. Enable this module by running the following command:
sudo a2enmod rewrite
Step 4: Restart Apache
Finally, restart Apache to apply the changes:
sudo systemctl restart apache2
After completing these steps, your Apache server will redirect URLs like domain/item/1
to item.php?name=1
, allowing your PHP script to handle the request dynamically based on the URL parameter. This is particularly useful when you're using pure PHP without a framework, as it simplifies handling of path parameters and query parameters.
Happy coding!