You are here
Home > Web Hosting > Apache > How To Setup mod_rewrite In Apache

How To Setup mod_rewrite In Apache

Mod_rewrite on Apache

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 Apache

Enable mod_rewrite

You will want to edit the main Apache configuration file

nano /etc/httpd/conf/httpd.conf

Add or un-comment the following line

LoadModule rewrite_module modules/mod_rewrite.so

Once you have saved the file you can go ahead and restart Apache

systemctl restart httpd

or  in CentOS 6 or below

service httpd restart

You 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 Examples

Rewrite domain.com to www.domain.com

RewriteEngine 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 / SSL

RewriteEngine 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 another

RewriteRule ^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 another

RewriteEngine 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.

 

Leave a Reply

Be the First to Comment!

Notify of
avatar
wpDiscuz
Top