How to Convert .htaccess Rules to NGINX Directives

Posted on by Kurtis Foley | Updated:
Reading Time: 6 minutes

NGINX is a web server that is becoming an increasingly popular option for web hosting, as sixteen percent of all sites on the internet are utilizing NGINX. This percentage is constantly increasing as clients require a web server that can serve content faster. It can also be used for proxies, reverse proxies, load balancing, and more depending on what modules you load onto NGINX. One of the significant differences between Apache (a popular webserver) and NGINX is the way each system handles access rules. If you are familiar with using .htaccess rules in Apache, then the method that NGINX uses of including directives in the server's vhost block will be a substantial change.

How to Convert .htaccess Rules to NGINX Directives

We will be showing how to convert .htaccess rewrite rules to NGINX rewrite directives. The NGINX rewrite directives will also need to be placed within the server block. Many server configurations include this server block information in the vhosts file, while some use a separate NGINX configuration file (for more information about the NGINX configuration file, see Redirecting URLs Using NGINX). To complete this task, you will need to understand some basic NGINX directives I will be discussing in the next session.

Introduction to NGINX Rewrite and Return Directives

The most commonly used directives with NGINX are the return and rewrite directives. When using an NGINX directive, a client visiting a page can be directed to a different directory or a different landing page. Requests can also be redirected to an application depending on the directives you specify. For example, clients visiting the page from a smartphone can be forwarded to a script that is coded specifically for phone browsers. Another example would be to forward a client based on IP or geographical location, making your site region-specific and tailored to the visitor based on location.

NGINX Return Directive

The return directive is a bit less complicated than the rewrite directive. The best practice is to use this directive over the rewrite directive whenever possible. You will typically include the return in a server context that specifies the domains to be rewritten. I have included a common example below. Clients visiting the site will be redirected to the domain specified after the 301 status code. Using this directive will forward the client that visits www.liquidwebtest.com to www.liquidweb.com.

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

NGINX Rewrite Directive

The rewrite directive is somewhat different than the rewrite rules in .htaccess. It needs to be placed 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 NGINX rewrite directive can get very complicated but once you understand the basic syntax it can be a lot less intimidating. I have included the basic syntax for an NGINX rewrite directive below.

rewrite regex URL [flag];

It is important to know a rewrite directive will almost always return a HTTP 301 or 302 status code. If you need your web server to return a different status code, the return directive is needed after the rewrite. I have included an example below from NGINX’s rewrite module documentation.

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.

Converting .htaccess rules to NGINX directives

Hopefully by this point we have a basic understanding of the two most commonly used NGINX directives. However, learning these rules will take some time as the can be very complex. Learning regular expressions is very helpful in this process. We’ll work through examples of commonly used .htaccess rules that we will be converting to NGINX directives.

Example: Redirecting from example.com to www.example.com

Adding the www to a URL when a client requests content from your server can help certain sites (like those hosted on WordPress) to function more efficiently. A common .htaccess rule to accomplish this rewrite is:

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

As we mentioned earlier it is best practice to use the return directive whenever possible. Below we will be creating a server block within the nginx.conf to accomplish the same task as the .htaccess rewrite rule above.

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

In this example there will be two server blocks defined with brackets” {}”. 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. The 2nd is not always needed but will serve content from the working directory if www.example.com is requested. If no exact match is found, NGINX then checks to see if there is a server_name with a starting wildcard that fits. The longest match beginning with a wildcard will be selected to fulfill the request.

You can test your syntax by running the following command:

nginx -t

This allows you to test the syntax for errors before loading the changes in the configuration file and possibly causing issues on your live site. Once you have edited the NGINX configuration file be sure to restart NGINX using a daemon or simply running the command below.

nginx -s reload

Example: WordPress Permalinks

In this example, I have included one of the most common sets of .htaccess rules used today. The rules I have included below allow WordPress to utilize permalinks. This is installed by default with WordPress on an Apache server. A permalink is a URL that is intended to remain unchanged. For example, domainexample.com/blogexample.php can be loaded as domainexample.com/blog within your browsers address bar.

<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. No return or rewrite directive is needed here as we are only allowing the content management system to hide the paths using permalinks. For more information on this task please seeNGINX's documentation on permalinks.

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

You can test your syntax by running the following command:

nginx -t

This allows you to test the syntax for errors before loading the changes in the configuration file and possibly causing issues on your live site. Once you have edited the NGINX configuration file be sure to restart NGINX using a daemon or simply running the command below.

nginx -s reload

Example: 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 (see What Is an SSL Certificate?). It can also be used to verify a business location, business ID number, and location. This helps prevent visiting malicious sites that may cause harm to your personal computer or private information.

The following .htaccess rule will force https, so that requests using port 80 for example.com will be redirected 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;
}

You can test your syntax by running the following command:

nginx -t

This allows you to test the syntax for errors before loading the changes in the configuration file and possibly causing issues on your live site. Once you have edited the NGINX configuration file be sure to restart NGINX using a daemon or simply running the command below.

nginx -s reload

Conclusion

We could go on and on with examples but hopefully, at this point, we now have a basic understanding of converting .htaccess for Apache to NGINX directives. If you require further information on accomplishing these tasks you can always reach out to our support for assistance. However, we do not fully support NGINX and it is considered Beyond Scope support. This means we will assist you as much as possible, but we may not be able to resolve your issue and may instead refer you to a developer for additional assistance. If you want to use the NGINX web server to host your content, we have multiple options including our VPS lineup to meet your business requirements. NGINX is currently being developed for use on cPanel servers as well, although it is not currently supported or recommended in production situations. See cPanel’s blog for more information.

Like What You See?

Contact us today at 1.800.580.4985 to speak to a knowledgeable Hosting Solutions Provider who can get you the info you need, to make an informed decision right away.

Too busy to talk? Click HERE to open a quick chat with us to find out more. Would you like the information in an email you can review at your leisure? Email us today to get solid advice on which product in our line up would best suit your needs.

We look forward to hearing from you!

Avatar for Kurtis Foley

About the Author: Kurtis Foley

Latest Articles

Blocking IP or whitelisting IP addresses with UFW

Read Article

CentOS Linux 7 end of life migrations

Read Article

Use ChatGPT to diagnose and resolve server issues

Read Article

What is SDDC VMware?

Read Article

Best authentication practices for email senders

Read Article