Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Arrow up icon
GO TO TOP
Mastering NGINX

You're reading from   Mastering NGINX Personalize, customize and configure NGINX to meet the needs of your server

Arrow left icon
Product type Paperback
Published in Jul 2016
Publisher
ISBN-13 9781782173311
Length 320 pages
Edition 2nd Edition
Tools
Arrow right icon
Author (1):
Arrow left icon
 Aivaliotis Aivaliotis
Author Profile Icon Aivaliotis
Aivaliotis
Arrow right icon
View More author details
Toc

Table of Contents (20) Chapters Close

Mastering NGINX - Second Edition
Credits
About the Author
About the Reviewer
www.PacktPub.com
Preface
1. Installing NGINX and Third-Party Modules FREE CHAPTER 2. A Configuration Guide 3. Using the mail Module 4. NGINX as a Reverse Proxy 5. Reverse Proxy Advanced Topics 6. The NGINX HTTP Server 7. NGINX for the Application Developer 8. Integrating Lua with NGINX 9. Troubleshooting Techniques Directive Reference
The Rewrite Rule Guide The NGINX Community Persisting Solaris Network Tunings
Index

Translating from Apache


There is a long history of writing rewrite rules for the powerful mod_rewrite module of Apache, and most resources on the Internet are focused on these rules. When encountering the rewrite rules in Apache's format, they can be translated into a form that NGINX can parse by following a few simple rules.

Rule #1 – Replacing directory and file existence checks with try_files

Encounter an Apache rewrite rule of the following form:

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php?q=$1 [L]

This can best be translated into an NGINX configuration as follows:

try_files $uri $uri/ /index.php?q=$uri;

These rules state that when the filename specified in the URI is neither a file nor a directory on disk, the request should be passed to the index.php file lying in the current context's root and given the q argument with a value matching the original URI.

Before NGINX had the try_files directive, there would be no choice but to use if to test for the existence of the URI:

if (!-e $request_filename) {

  rewrite ^/(.*)$ /index.php?q=$1 last;

}

Don't do this. You may see configurations on the Internet that recommend doing exactly this, but they are outdated or are copies of an outdated configuration. While not strictly a rewrite rule, because try_files belongs to the core http module, the try_files directive is much more efficient at performing this task and this is exactly what it was created for.

Rule #2 – Replacing matches against REQUEST_URI with a location

Many Apache rewrite rules are made to be placed into the .htaccess files because, historically, users would most likely have access to these files themselves. A typical shared hoster would not enable their users' direct access to the virtual host configuration context responsible for their website, but would instead offer the ability to place nearly any kind of configuration into an .htaccess file. This led to the situation we have today, with a proliferation of the .htaccess-file-specific rewrite rules.

While Apache also has a location directive, it is rarely used to solve the problem of matching the URI because it may only be used in either the main server configuration or the configuration of a virtual host. So, instead we see a proliferation of rewrite rules that match REQUEST_URI:

RewriteCond %{REQUEST_URI} ^/niceurl

RewriteRule ^(.*)$ /index.php?q=$1 [L]

This is best handled in NGINX by using location:

location /niceurl {

  include fastcgi_params;

  fastcgi_index index.php;

  fastcgi_pass 127.0.0.1:9000;

}

Of course, what is inside the location context is dependent upon your setup, but the principle remains the same; matches against the URI are best served by location.

This principle also applies to RewriteRules that have an implicit REQUEST_URI. These are typically bare RewriteRules that transform the URI from an older format to a newer one. In the following example, we see that show.do is no longer necessary:

RewriteRule ^/controller/show.do$ http://example.com/controller [L,R=301]

This code translates to an NGINX configuration as follows:

location = /controller/show.do {

  rewrite ^ http://example.com/controller permanent;

}

Not to get too carried away with creating locations whenever we see RewriteRule, we should keep in mind that regular expressions translate directly.

Rule #3 – Replacing matches against HTTP_HOST with a server

Related closely to the rule mentioned in the Rule #2 – Replacing matches against REQUEST_URI with a location section, this rule takes configurations into account that try to either remove or add a www onto a domain name. These types of rewrite rule are often found in .htaccess files or in virtual hosts with overloaded ServerAliases:

RewriteCond %{HTTP_HOST} !^www

RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Here, we translate the case where no www is found at the beginning of the Host part of the URL to the variant with a www there:

server {

  server_name example.com;

  rewrite ^ http://www.example.com$request_uri permanent;

}

In the opposite case, where no www is desired, we enter the following rule:

RewriteCond %{HTTP_HOST} ^www

RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

This rule translates to the following NGINX configuration:

server {

  server_name www.example.com;

  rewrite ^ http://example.com$request_uri permanent;

}

What is not shown is the server context for the variant that has been redirected. This has been left out because it's not relevant to the rewriting itself.

Tip

This same principle applies to more than just matching www or lack thereof. It can be used in dealing with any RewriteCond that uses %{HTTP_HOST}. These rewrites are best done in NGINX by using multiple server contexts, one each to match the desired condition.

For example, we have the following multisite configuration in Apache:

RewriteCond %{HTTP_HOST} ^site1

RewriteRule ^(.*)$ /site1/$1 [L]

RewriteCond %{HTTP_HOST} ^site2

RewriteRule ^(.*)$ /site2/$1 [L]

RewriteCond %{HTTP_HOST} ^site3

RewriteRule ^(.*)$ /site3/$1 [L]

This basically translates to a configuration that matches by hostname and has a different root configuration per host:

server {

  server_name site1.example.com;
  root /home/www/site1;

}

server {

  server_name site2.example.com;

  root /home/www/site2;

}

server {

  server_name site3.example.com;

  root /home/www/site3;

}

These are essentially different virtual hosts, so it is best to treat them as such in the configuration as well.

Rule #4 – Replacing RewriteCond with if for variable checks

This rule applies only after having applied the rules mentioned in the Rule #1 – Replacing directory and file existence checks with try_files, Rule #2 – Replacing matches against REQUEST_URI with a location, and Rule #3 – Replacing matches against HTTP_HOST with a server sections. If there are any remaining conditions not covered by those rules, if may be applied to test the values of variables. Any HTTP variable may be used by prefixing the lowercased name of the variable with $http_. If there are hyphens (-) in the name, these are translated into underscores (_).

The following example (taken from Apache's documentation on the mod_rewrite module at http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html) is used to decide the page that should be delivered to a client based on the User-Agent header:

RewriteCond %{HTTP_USER_AGENT} ^Mozilla

RewriteRule ^/$ /homepage.max.html [L]

RewriteCond %{HTTP_USER_AGENT} ^Lynx
RewriteRule ^/$ /homepage.min.html [L]

RewriteRule ^/$ /homepage.std.html [L]

This rule can be translated to an NGINX configuration as follows:

if ($http_user_agent ~* ^Mozilla) {

  rewrite ^/$ /homepage.max.html break;

}

if ($http_user_agent ~* ^Lynx) {

  rewrite ^/$ /homepage.min.html break;

}

index homepage.std.html;

If there are any special variables that are available only under Apache's mod_rewrite, these of course can't be checked in NGINX.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime
Visually different images