How To Enable mod_rewrite In Nginx

This tutorial help to enable mod_rewrite in nginx server .The .htaccess is not supported by Nginx server, So will implement URL routing into nginx using site virtual host file. The URL Rewrite use to make URLs Search Engine Friendly.

The mod_rewrite module normally uses a rule-based rewriting engine to rewrite requested URLs based on PCRE regular-expression parser. By defaults mod_rewrite maps a URL to a filesystem path. It allows you to rewrite URL based on server variables, environment variables, HTTP headers, or time stamps.

The Apache server is supporting .htaccess file. I have already shared How To Enable Mod_Rewrite Module In Apache

Nginx Mod_Rewrite URL Example

I am assuming you have CentOS machine and Nginx is installed on it. There are following steps will follow to implement URL rewrite rules –

Step 1: I am assuming you’re using the default.conf file. We will open this file which is stored in /etc/nginx/conf.d/ folder –

Step 2: Search the below code into the virtual host file( default.conf ).

location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
    }

We will make following changes into the above line and save the file –

location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.php?$args;
    }

Step 3: We will reload Nginx server service using below command –
sudo service nginx reload

How To Enable Mod_Rewrite for Subfolder

Normally, web hosting provider install WordPress site into the sub folder( phpflow ) then , We need to change location block as like below –

from –

location / {
index index.php index.html index.htm;
try_files $uri $uri/ /index.php?$args;
}

replace To –

location /phpflow/ {
try_files $uri $uri/ /wordpress/index.php?$args;

You need to restart nginx service or server.

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *