The Apache module mod_rewrite allows you to rewrite URL requests that come into your server. It is useful if you want to redirect the requests to a subdirectory, change http to https, etc. In this tutorial, I will show you how to write a simple rewrite rule.
Enable your server to accept .htaccess
First, you need to enable your Apache server to accept .htaccess file because by default, it doesn't allow the use of .htaccess file. You need to add the following codes inside the <VirtualHost *:80>
section of
/etc/apache2/sites-available/000-default.conf.
<VirtualHost *:80> <Directory /var/www/html> Options Indexes FollowSymLinks MultiViews AllowOverride All Require all granted </Directory> </VirtualHost>
Then, restart Apache server for the changes to take effect.
systemctl restart apache2
Simple rewrite rule
Put the following rule in /var/www/html/.htaccess.
RewriteEngine on RewriteRule ^a.html$ /bbbb.html [NE,R]
^
: Indicate that we are matching any text after the server IP address or domain name(e.g. http://localhost/ or http://127.0.0.1/).$
: Indicate the end of the URL that we are matching./
: Set the root path. Otherwise, it will redirect to http://localhost/var/www/html/bbbb.html.NE
: Don't escape special characters such as &, ?, #, etc.R
: Instruct RewriteRule to redirect.
Test rewrite rule
Open http://localhost/a.html with your browser. It will automatically redirect to http://localhost/bbbb.html.
Reference
- https://httpd.apache.org/docs/2.4/rewrite/flags.html