mod_rewrite is a Apache module installed on linux servers to manipulate URLs submitted in the browser to perform other functions than it appears. Mod_rewrite can improve SEO appearing to give it a static appearance.This guide assumes you already have Apache installed, if you do not please see How to Install ApacheEnable mod_rewriteYou will want to edit the main Apache configuration filenano /etc/httpd/conf/httpd.confAdd or un-comment the following lineLoadModule rewrite_module modules/mod_rewrite.soOnce you have saved the file you can go ahead and restart Apachesystemctl restart httpdor in CentOS 6 or belowservice httpd restartYou should now see the module loaded by doing the following command# httpd -M 2>&1|grep rewrite
rewrite_module (shared)That is for enabling the module. Mod_rewrite rules can either be inserted directly into the VirtualHost block for a specific domain or in a .htaccess for that given domain.Mod_rewrite ExamplesRewrite domain.com to www.domain.comRewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]The above redirect will take all requests to the non-www domain and redirect them with a 301 code to the www.domain.com url and appendedthe rest of the url to it.Redirect all requests to https / SSLRewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.com [NC]
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI}The above redirect will take all non-ssl requests and redirect them to https:// URLs.Redirect request from one directory to anotherRewriteRule ^subdirectory/(.*)$ /anotherdirectory/$1 [R=301,NC,L]The above redirect will take any requests towards a single directory and redirect it to another directory with the rest of URL appended to it.Redirect one domain to anotherRewriteEngine On
RewriteCond %{HTTP_HOST} ^olddomain.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.olddomain.com [NC]
RewriteRule ^(.*)$ http://newdomain.com/$1 [L,R=301,NC]This will redirect any requests with the destination of the olddomain and change them to the new domain. There are numerous redirects you can perform with mod_rewrite these are just a couple of common examples. Sep 5, 2017LinuxAdmin.io