Updating the htaccess file with the RewriteRule directive instructs the web server (and search engines) to look for the requested URL in a new or alternate location on the server. This is can be used if your site structure has changed and pages are physically elsewhere or more importantly if a page URL no longer exists as a result of search optimisation changes.
Suppose we have a page on our site such as: https://www.miromedia.co.uk/seo/ and the â€˜seo’ page has its URL changed to â€˜search-engine-optimisation’ this would mean that the new URL would be: https://www.miromedia.co.uk/search-engine-optimisation/. For links to the old page the search engines and users would receive a 404 Page Not Found error.
We need to redirect the old URL to the new one and do this by updating the .htaccess file as follows:
RewriteRule ^seo/ https://www.miromedia.co.uk/search-engine-optimisation/ [L,R=301]
This example takes the URL request to â€˜seo/’ (the ^ signifies the incoming request matches on everything after the domain i.e. https://www.miromedia.co.uk/) and redirects it to the new URL. The R instructs the web server to redirect and to do so using with the HTTP response code 301 (Moved Permanently).
The L instructs the server to stop processing here and to not apply anymore rewriting rules.
An alternative use of the RewriteRule directive is to allow the website to interpret highly optimised URLs into query string type requests. All Miromedia sites are built using a database and so pages are served up in the code using IDs. With the RewriteRule we can output human readable URLs that are optimised for search engine and makes sense to the user but then interpret these as more complex query strings once on the server.
We add a line like this one to the htaccess file:
RewriteRule ^([^/]+)/$ index.php?main=page&pageUrl=$1 [L]
Which will make a regular expression match on all text after the domain and before the first instance of the forward slash and pass this to the web server as the data for the pageUrl parameter in the query string. The website code then takes this pageUrl parameter data and returns the page content for the page in the database that matches it. The L then instructs the server to not process anymore rewrite rules.
So this request: https://www.miromedia.co.uk/seo/ would be seen by the web server as: https://www.miromedia.co.uk/index.php?main=page&pageUrl=seo
The RewriteRule makes use of the Regular Expression syntax to allow you to build very clever and complex matches on the requested URL to redirect as you need.