Bobcares

How to convert common .htaccess rules to NGINX directives?

by | Oct 26, 2020

Wondering how to convert .htaccess rules to NGINX directives?

As a part of our Server Management Services, we help our Customers with NGINX related requests regularly.

Let us today discuss the steps to convert common .htaccess rules to NGINX directives.

NGINX Rewrite and Return Directives

The most commonly used directives with NGINX are the return and rewrite directives.

When using an NGINX directive, it can direct a client visiting a page to a different directory or a different landing page. Further, it can also redirect requests to an application depending on the directives we specify.

 

NGINX Return Directive

It is a best practice to use the return directive over the rewrite directive whenever possible as it is a bit less complicated than the rewrite directive.

We will typically include the return in a server context that specifies the domains to be rewritten. For instance, using the directive in the following format will forward a client that visits www.bobcarestest.com to www.bobcares.com.

server {
listen 80;
server_name www.bobcarestest.com;
return 301 $scheme://www.bobcares.com$request_uri;
}

 

NGINX Rewrite Directive

The rewrite directive is somewhat different than the rewrite rules in .htaccess. We need to place it in a specific location or server block to rewrite the URL.

The rewrite directive is usually used to perform smaller tedious tasks.

For example, it is used in some cases to capture elements in the original URL or change elements in the path. The basic syntax for an NGINX rewrite directive is given below.

rewrite regex URL [flag];

It is important to note that a rewrite directive will almost always return an HTTP 301 or 302 status code. If we need the webserver to return a different status code, the return directive needs to be added after the rewrite.

For example,

server{
...
rewrite ^(/download/.*)/media/(.*)..*$ $1/mp3/$2.mp3 last;
rewrite ^(/download/.*)/audio/(.*)..*$ $1/mp3/$2.ra last;
return 403;
...
}

In this example, the URLs that start with /download followed by /media or /audio are matched. Afterwards, directories /media and /audio elements that contain /mp3 will have the extension .mp3 or .ra file extension added to the URL.

This return directive will return a 403 to the client if the URL does not match the rewrite rule.

 

Convert .htaccess rules to NGINX directives

Let us see a few examples of commonly used .htaccess rules that we will be converting to NGINX directives.

Redirecting from example.com to www.example.com

Adding the www to a URL when a client requests content from the server can help certain sites to function more efficiently. A common .htaccess rule to accomplish this rewrite is:

RewriteCond %{HTTP_HOST} example.com
RewriteRule (.*)https://www.example.com$1

Below we will be creating a server block within the nginx.conf to accomplish the same task:

server {
listen 80;
server_name example.com;
return 301 http://www.example.com
$request_uri;
}
server {
listen 80'
server_name www.example.com;
#...
}

We are telling NGINX to listen on port 80 for requests to example.com. Then to return a 301 ”redirection” to www.example.com.

We usually split these rules into two server blocks to make these directives as efficient as possible.  We don’t always need the second block but will serve content from the working directory, once it requests www.example.com.

If no exact match is found, NGINX then checks to see if there is a server_name with a starting wildcard that fits. It then selects the longest match beginning with a wildcard to fulfill the request.

Finally, we can test your syntax by running the following command:

$ nginx -t

This allows us to test the syntax for errors before loading the changes in the configuration file.

Once we have edited the NGINX configuration file be sure to restart NGINX using a daemon or simply running the command below.

$ nginx -s reload

 

WordPress Permalinks

By default, WordPress includes the following rules to allow it to utilize permalinks on an Apache server:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond ${REQUEST_FILENAME} ~ - f
RewriteCond ${REQUEST_FILENAME} ~ - d
RewriteRule . /index.php [L]
<IfModule>

Below is the NGINX equivalent. It does not require any return or rewrite directive here as we are only allowing the content management system to hide the paths using permalinks.

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

Finally, we can test the syntax by running the following command and then restart NGINX

$ nginx -t

$ nginx -s reload

 

Forcing http to https

Another popular use for the .htaccess file is to force the browser to load the site using https over HTTP. This allows the browser to verify the site is not a security risk by confirming the site exists on the server it claims to be on.

The following .htaccess rule will force https so that it redirects the requests using port 80 for example.com to https://www.example.com.

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]

To accomplish this with NGINX, we will use the NGINX return directive.

server {
listen 80;
server_name example.com;
return 301 https://www.example.com$request_uri;
}

Finally, test the syntax and reload NGINX as we did in the steps earlier.

[Need any further assistance to convert htaccess to nginx directives? – We’re available 24*7]

 

Conclusion

In short, while converting the .htaccess rewrite rules to NGINX rewrite directives, we need to keep the directives within the server block. Today, we saw how our Support Engineers perform this task.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = "owonCMyG5nEQ0aD71QM";

0 Comments

Submit a Comment

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

Never again lose customers to poor
server speed! Let us help you.

Privacy Preference Center

Necessary

Necessary cookies help make a website usable by enabling basic functions like page navigation and access to secure areas of the website. The website cannot function properly without these cookies.

PHPSESSID - Preserves user session state across page requests.

gdpr[consent_types] - Used to store user consents.

gdpr[allowed_cookies] - Used to store user allowed cookies.

PHPSESSID, gdpr[consent_types], gdpr[allowed_cookies]
PHPSESSID
WHMCSpKDlPzh2chML

Statistics

Statistic cookies help website owners to understand how visitors interact with websites by collecting and reporting information anonymously.

_ga - Preserves user session state across page requests.

_gat - Used by Google Analytics to throttle request rate

_gid - Registers a unique ID that is used to generate statistical data on how you use the website.

smartlookCookie - Used to collect user device and location information of the site visitors to improve the websites User Experience.

_ga, _gat, _gid
_ga, _gat, _gid
smartlookCookie
_clck, _clsk, CLID, ANONCHK, MR, MUID, SM

Marketing

Marketing cookies are used to track visitors across websites. The intention is to display ads that are relevant and engaging for the individual user and thereby more valuable for publishers and third party advertisers.

IDE - Used by Google DoubleClick to register and report the website user's actions after viewing or clicking one of the advertiser's ads with the purpose of measuring the efficacy of an ad and to present targeted ads to the user.

test_cookie - Used to check if the user's browser supports cookies.

1P_JAR - Google cookie. These cookies are used to collect website statistics and track conversion rates.

NID - Registers a unique ID that identifies a returning user's device. The ID is used for serving ads that are most relevant to the user.

DV - Google ad personalisation

_reb2bgeo - The visitor's geographical location

_reb2bloaded - Whether or not the script loaded for the visitor

_reb2bref - The referring URL for the visit

_reb2bsessionID - The visitor's RB2B session ID

_reb2buid - The visitor's RB2B user ID

IDE, test_cookie, 1P_JAR, NID, DV, NID
IDE, test_cookie
1P_JAR, NID, DV
NID
hblid
_reb2bgeo, _reb2bloaded, _reb2bref, _reb2bsessionID, _reb2buid

Security

These are essential site cookies, used by the google reCAPTCHA. These cookies use an unique identifier to verify if a visitor is human or a bot.

SID, APISID, HSID, NID, PREF
SID, APISID, HSID, NID, PREF