Tutorials

Install and Configure mod_rewrite for Apache on CentOS 7

Table of Contents

Introduction

Apache's mod_rewrite can be used to manipulate URLs. It is compiled into the base Apache Web Server. This module provides the ability to manipulate URLs prior to determining the appropriate file or handing off to a script. It can help you, if you want to offer different URLs for the same file. This is most commonly used when a visitor goes to a certain web address, but the server returns a different page. This module uses a rule-based rewriting engine to rewrite requested URLs on the fly. It supports an unlimited number of rules to provide a really flexible and powerful URL manipulation mechanism. It can hide sensitive information, such as query strings, from URL requests. This can potentially enhance website safety.

In this tutorial, we will explain how to enable mod_rewrite and demonstrate some common ways to use it in Apache on CentOS 7.

Requirements

  • A server running CentOS 7

Install Apache

Before we begin with the mod_rewrite module setup, we need to install the Apache web server.

To install Apache, run the following command:

sudo yum install httpd -y

After installing Apache, start the httpd service and enable it to start automatically on boot.

We can do this using the following commands:

sudo systemctl start httpd.service
sudo systemctl enable httpd.service

Next, we should allow access to the default Apache port 80 (HTTP) using firewalld.

We can do this by running the following command:

sudo firewall-cmd --permanent --add-port=80/tcp

Now, reload the firewall service for the changes to take effect.

sudo systemctl restart firewalld.service

Enable mod_rewrite Module

The mod_rewrite module is enabled by default on CentOS 7. If you find it is not enabled on your server, you can enable it by editing 00-base.conf file located in /etc/httpd/conf.modules.d/ directory.

sudo nano /etc/httpd/conf.modules.d/00-base.conf

Add or uncomment the following line:

LoadModule rewrite_module modules/mod_rewrite.so

Save and close the file, then restart the httpd service:

sudo systemctl restart httpd

Enable .htaccess File

Once the mod_rewrite module has been activated, you can set up your URL rewrites by creating an .htaccess file in your default document root directory. A .htaccess file allows us to modify our rewrite rules without accessing server configuration files. For this reason, .htaccess is critical to your web server. Before we begin, we need to allow Apache to read .htaccess files located under the /var/www/html directory.

You can do this by editing httpd.conf file:

sudo nano /etc/httpd/conf/httpd.conf

Find the section <directory /var/www/html> and change AllowOverride None to AllowOverride All

 <Directory /var/www/html>
    AllowOverride All
 </Directory>

Save and exit.

Now restart Apache to put the change into effect:

sudo systemctl restart httpd

Configure Rewrite Module

In this section, we will explain basic mod_rewrite syntax and give some examples.

You can write RewriteRules using the following format:

RewriteRule pattern substitution [flags]
  • RewriteRule: This directive specifies the name of the the mod_rewrite directive that you want to use.
  • Pattern: This directive specifies a regular expression that matches the desired string
  • Substitution: This directive specifies the path of the actual URL of the page with the information you want to display.
  • Flags: A flag is a tag at the end of the Rewrite Rule directive that specifies optional parameters that can modify the rule.

Let's discuss RewriteRules with some examples:

Redirect www to non-www

If you want to redirect users from www to a plain non-www domain, you will need to create .htaccess file in Apache document root directory.

Change directories to your Document root:

cd /var/www/html

Create the .htaccess file:

sudo nano .htaccess

Add the following content:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Save and exit the file.

We can use curl to test that the www domain redirects to the non-www domain:

curl -I http://www.yourdomain.com

You should see the following output:

HTTP/1.1 301 Moved Permanently
Date: Mon, 03 May 2016 18:20:53 GMT
Server: Apache/2.4.6 (CentOS)
Location: http://yourdomain.com/
Content-Type: text/html; charset=iso-8859-1

Above output shows the non-www redirect location http://yourdomain.com/

Redirect non-www to www

If you want to redirect users from a plain non-www domain to a www domain, add the following content to your .htaccess file:

sudo nano /var/www/html/.htaccess

Add the following content:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

Save and exit the file.

Now, use curl command to ensure that the non-www domain redirects to the www domain:

curl -I http://yourdomain.com

You should see the following output:

HTTP/1.1 301 Moved Permanently
Date: Mon, 03 May 2016 18:20:53 GMT
Server: Apache/2.4.6 (CentOS)
Location: http://www.yourdomain.com/
Content-Type: text/html; charset=iso-8859-1

Above output shows the www redirect location http://www.yourdomain.com/

Redirect All Website Pages

If you want to redirect all pages from "olddomain.com" to "newdomain.com", edit the .htaccess file:

sudo nano /var/www/html/.htaccess

Add the following content:

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^www.olddomain.com$ [OR]
RewriteCond %{HTTP_HOST} ^olddomain.com$
RewriteRule ^(.*)$ http://www.newdomain.com/$1 [R=301,L]

Save and exit the file.

Now, use curl to test that the "www.olddomain.com" domain redirects to the "www.newdomain.com" domain:

curl -I http://www.olddomain.com

You should get a 301 Moved Permanently response that shows you the new domain redirect location.

Deny File Type Access

If you want to deny users to access specific file types such as: .pdf, .css, .gif, .png, or .bmp then edit your .htacces file:

sudo nano /var/www/html/.htaccess

Add the following content:

RewriteEngine on
RewriteRule .*\.(pdf|css|gif|png|bmp)$ - [F,NC]

Save and exit the file.

Summary

Those are just a few examples of how mod_rewrite can be used. If you have questions about these examples please let us know below. You are also welcome to post in the ProfitBricks DevOps Community section of this site.

 
  • I want to redirect social media crawlers to a separate snapshot page using the VirtualHost. This is how I have written the virtual host:

    NameVirtualHost *:80

    <virtualhost *:80="">

    ServerName www.mysite.com DocumentRoot /var/www/html/

    <directory var="" www="" html=""/> Allow From All RewriteEngine On RewriteCond %{HTTP_USER_AGENT} (facebookexternalhit/[0-9]|Twitterbot|Pinterest|Google.*snippet) RewriteRule . http://www.mysite.com/snapshot [L] </directory>

    </virtualhost>

    After using this virtual host rule, social media crawling is working fine, but the site stops working, it gives index page not found error.

    Please help me to write a correct virtual host.

  • Thanks!!! Good luck ))))

  • Need help with Apache start error. I can not start it after my failed attempt to install ISPConfig3 on Centos7. I uninstalled and reinstalled apache; but it is giving the same error message. I do not see any syntax error in line 353. Thanks a lot for the help.

    [root@test1 mnasimul]# systemctl status -l httpd

    ● httpd.service - The Apache HTTP Server

    Loaded: loaded (/usr/lib/systemd/system/httpd.service; enabled; vendor preset: disabled)

    Active: failed (Result: exit-code) since Thu 2017-05-11 15:31:55 EDT; 14min ago

    Docs: man:httpd(8)

    man:apachectl(8)

    Process: 3695 ExecStop=/bin/kill -WINCH ${MAINPID} (code=exited, status=1/FAILURE)

    Process: 3685 ExecStart=/usr/sbin/httpd $OPTIONS -DFOREGROUND (code=exited,

    status=1/FAILURE)

    Main PID: 3685 (code=exited, status=1/FAILURE)

    May 11 15:31:55 test1.nasim.com systemd[1]: Starting The Apache HTTP Server...

    May 11 15:31:55 test1.nasim.com httpd[3685]: httpd: Syntax error on line 353 of

    /etc/httpd/conf/httpd.conf: Syntax error on line 1 of /etc/httpd/conf.d/suphp.conf: Cannot load

    modules/mod_suphp.so into server: /etc/httpd/modules/mod_suphp.so: cannot open shared object file:

    No such file or directory

    May 11 15:31:55 test1.nasim.com systemd[1]: httpd.service: main process exited, code=exited,

    status=1/FAILURE

    May 11 15:31:55 test1.nasim.com kill[3695]: kill: cannot find process ""

    May 11 15:31:55 test1.nasim.com systemd[1]: httpd.service: control process exited, code=exited

    status=1

    May 11 15:31:55 test1.nasim.com systemd[1]: Failed to start The Apache HTTP Server.

    May 11 15:31:55 test1.nasim.com systemd[1]: Unit httpd.service entered failed state.

    May 11 15:31:55 test1.nasim.com systemd[1]: httpd.service failed.

  • Redirect from one site to another does not work at all. should i install mod_rewrite module for this or only enough to add entry LoadModule rewrite_module modules/mod_rewrite.so for this?

  • I can not start it after my failed attempt to install ISPConfig3 on Centos7. I uninstalled and reinstalled apache; but it is giving the same error message. I do not see any syntax error in line 353. Thanks a lot for the help. and for the help you can visit Epson error code 0x97 and get the solution

  • We are one stop solution for your printer issue. Make a call on 1-877-916-7666

    Assistance for all is an amazing and one of the biggest printer support service providers in the USA. Our customer-centric process helps us to understand the specific requirements of our clients and helps us to come to the best possible conclusion for them.

    We are also knom for offering printer driver support services which are crafted under the aegis of the expert professionals. More Website - https://www.assistanceforall.com/services/printer-support/

  • Are you looking for a printer support service? Call us at 1-877-916-7666

    Printers in the present era become an integral part of our day to day life. From offices to home, printers have made their places according to their needs, requirements, and sizes.

  • To work more on this topic, I suggest you to look at https://www.topamericanwriters.com/essayontime-com-review/ because it's the exactly the same thing. It will help you like it helped me a lot. Thank you once again.

  • This module provides the ability to manipulate URLs prior to determining the appropriate file or handing off to a script.

    If anyone faces Brother Printer issue or any other printer issue get help from this Brother Printer Support

  • This is most commonly used when a visitor goes to a certain web address, but the server returns a different page. If anyone face printer error gets help from this printer not activated error code 20

  • If you are stuck anywhere or finding it difficult to find a way out, you can talk to Brother Printer Tech Support Number and get instant help regarding the installation of printer drivers on your system.

  • How to Install Brother Printer Setup?

    When you decide to install the printer driver with the help of USB or Parallel cable, you might face problems in the installation of original brother printer driver. The built-in driver of windows might have been installed. As you know, the built-in drivers provide support only for the fundamental functioning of the brother systems; it is recommended to use the brother original printer driver instead. You can contact on Brother Printer Support Number to get immediate help regarding the installation of printer drivers on your system

  • If you are stuck anywhere or finding it difficult to find a way out, you can talk to Brother Printer Tech Support Number and get instant help regarding the installation of printer drivers on your system.

  • Look for the solutions only after you have identified the actual reason for this error to occur in your system. For resolve any type of issue then visit:

    https://www.hptechnicalsupportphonenumbersusa.com/blog/hp-printer-in-error-state/

  • With the goal for this to work, a printer driver must be introduced on the Terminal Server that matches the driver introduced on the nearby PC. This is risky since you can't simply make sure which printer is introduced on associating PCs. View Epson Error Code 0xf1 to tackle problems of printer.

  • He just lives as if he never died. Just enjoy it, rest ... it begs to be bet like game: happy wheels basketball legends game

  • Hey! I can set up my URL rewrites by creating an .htaccess file in your default document root directory. A .htaccess file allows us to modify our rewrite rules without accessing server configuration files. If anyone having issues regarding to canon printer offline just follow this link.

  • A good blog always comes-up with new and exciting information and while reading I have feel that this blog is really have all those quality that qualify a blog to be a one. happy wedding anniversary wishes

Log In, Add a Comment