Mastering Nginx

(Ron) #1
Appendix B

[ 275 ]

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 translates to the following NGINX configuration:


server {

server_name http://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.


This same principle applies to more than just matching a www or lack of one. 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 on hostname and has a


different root configuration per host.


server {

server_name site1.example.com;
Free download pdf