How to Convert .htaccess Rules to NGINX Directives

Reading Time: 6 minutes

NGINX is a webserver that is becoming an increasingly popular option for webhosting, as sixteen percent of all sites on the internet are utilizing NGINX. This percentage is constantly increasing as clients are in need of 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 substantial change.

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 of the 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. 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;
}

  • Server { } is defining the block
  • Listen “what port to listen to”
  • Server_name “defining the incoming requested URL”
  • Return “what the server returns from this request”

NGINX Rewrite Directive

The rewrite directive is somewhat different that the rewrite rules in .htaccess. It needs to be placed in a specific location or server block in order 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 a 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 expression 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 I 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 in 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 set 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>

Belowis 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 see NGINX’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 on 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 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.

How to Redirect URLs Using Nginx

Reading Time: 3 minutes

What is a Redirect?

A redirect is a web server function that will redirect traffic from one URL to another. Redirects are an important feature when the need arises. There are several different types of redirects, but the more common forms are temporary and permanent. In this article, we will provide some examples of redirecting through the vhost file, forcing a secure HTTPS connection, redirection to www and non-www as well as the difference between temporary and permanent redirects.

Note
As this is an Nginx server, any .htaccess rules will not apply. If your using the other popular web server, Apache, you’ll find this article useful.

Common Methods for Redirects

Temporary redirects (response code: 302 Found) are helpful if a URL is temporarily being served from a different location. For example, these are helpful when performing maintenance and can redirect users to a maintenance page.

However, permanent redirects (response code: 301 Moved Permanently) inform the browser there was an old URL that it should forget and not attempt to access anymore. These are helpful when content has moved from one place to another.

 

How to Redirect

When it comes to Nginx, that is handled within a .conf file, typically found in the document root directory of your site(s), /etc/nginx/sites-available/directory_name.conf. The document root directory is where your site’s files live and it can sometimes be in the /html if you have one site on the server. Or if your server has multiple sites it can be at /domain.com.  Either way that will be your .conf file name. In the /etc/nginx/sites-available/ directory you’ll find the default file that you can copy or use to append your redirects. Or you can create a new file name html.conf or domain.com.conf.

Note
If you choose to create a new file be sure to update your symbolic links in the /etc/nginx/sites-enabled. With the command:

ln -s /etc/nginx/sites-available/domain.com.conf /etc/nginx/sites-enabled/domain.com.conf

The first example we’ll cover is redirection of a specific page/directory to the new page/directory.

Temporary Page to Page Redirect

server {
# Temporary redirect to an individual page
rewrite ^/oldpage$ http://www.domain.com/newpage redirect;
}

Permanent Page to Page Redirect

server {
# Permanent redirect to an individual page
rewrite ^/oldpage$ http://www.domain.com/newpage permanent;
}

Permanent www to non-www Redirect

server {
# Permanent redirect to non-www
server_name www.domain.com;
rewrite ^/(.*)$ http://domain.com/$1 permanent;
}

Permanent Redirect to www

server {
# Permanent redirect to www
server_name domain.com;
rewrite ^/(.*)$ http://www.newdomain.com/$1 permanent;
}

Sometimes the need will arise to change the domain name for a website. In this case, a redirect from the old sites URL to the new sites URL will be very helpful in letting users know the domain was moved to a new URL.

The next example we’ll cover is redirecting an old URL to a new URL.

Permanent Redirect to New URL

server {
# Permanent redirect to new URL
server_name olddomain.com;
rewrite ^/(.*)$ http://newdomain.com/$1 permanent;
}

We’ve added the redirect using the rewrite directive we discussed earlier. The ^/(.*)$ regular expression will use everything after the / in the URL. For example, http://olddomain.com/index.html will redirect to http://newdomain.com/index.html. To achieve the permanent redirect, we add permanent after the rewrite directive as you can see in the example code.

When it comes to HTTPS and being fully secure it is ideal for forcing everyone to use https:// instead of http://.

Redirect to HTTPS

server {
# Redirect to HTTPS
listen      80;
server_name domain.com www.domain.com;
return      301 https://example.com$request_uri;
}

After these rewrite rules are in place, testing the configuration prior to running a restart is recommended. Nginx syntax can be checked with the -t flag to ensure there is not a typo present in the file.

Nginx Syntax Check

nginx -t

If nothing is returned the syntax is correct and Nginx has to be reloaded for the redirects to take effect.

Restarting Nginx

service nginx reload

For CentOS 7 which unlike CentOS 6, uses systemd:

systemctl restart nginx

Redirects on Managed WordPress/WooCommerce

If you are on our Managed WordPress/WooCommerce products, redirects can happen through the /home/s#/nginx/redirects.conf file. Each site will have their own s# which is the FTP/SSH user per site. The plugin called ‘Redirection’ can be downloaded to help with a simple page to page redirect, otherwise the redirects.conf file can be utilized in adding more specific redirects as well using the examples explained above.

Due to the nature of a managed platform after you have the rules in place within the redirects.conf file, please reach out to support and ask for Nginx to be reloaded. If you are uncomfortable with performing the outlined steps above, contact our support team via chat, ticket or a phone call.  With Managed WordPress/WooCommerce you get 24/7 support available and ready to help you!

Troubleshooting: Too Many Redirects

Reading Time: 7 minutes

The error “too many redirects” means that the website keeps being redirected between different addresses in a way that will never complete. Often this is the result of competing redirects, one trying to force HTTPS (SSL) and another redirecting back to HTTP (non-SSL), or between www and non-www forms of the URL.

Continue reading “Troubleshooting: Too Many Redirects”

Understanding the Default WordPress .htaccess

Reading Time: 3 minutes

When maintaining a WordPress site you may find yourself attempting things that normally would work and find that they have unexpected results. This is usually due to how WordPress’ default .htaccess rules manipulate the configurations and provide ‘pretty permalinks’.

Continue reading “Understanding the Default WordPress .htaccess”