Converting rewrite rules

nginx


news
about
download
security advisories
documentation
introduction
howto
wiki
links
support
Converting Mongrel rules

A redirect to a main site

People who during their shared hosting life used to configure everything using only Apache’s .htaccess files, translate usually the following rules:

RewriteCond  %{HTTP_HOST}  nginx.org
RewriteRule  (.*)          http://www.nginx.org$1

in something like this:

server {
    listen       80;
    server_name  www.nginx.org  nginx.org;
    if ($http_host = nginx.org) {
        rewrite  (.*)  http://www.nginx.org$1;
    }
    ...
}

This is a wrong, cumbersome, and ineffective way. The right way is to define a separate server for nginx.org:

server {
    listen       80;
    server_name  nginx.org;
    rewrite   ^  http://www.nginx.org$request_uri?;
}

server {
    listen       80;
    server_name  www.nginx.org;
    ...
}

Another example, instead of backward logic: all that is not nginx.com and is not www.nginx.com:

RewriteCond  %{HTTP_HOST}  !nginx.com
RewriteCond  %{HTTP_HOST}  !www.nginx.com
RewriteRule  (.*)          http://www.nginx.com$1

you should define just nginx.com, www.nginx.com, and anything else:

server {
    listen       80;
    server_name  nginx.org  www.nginx.org;
    ...
}

server {
    listen       80 default_server;
    server_name  _;
    rewrite   ^  http://nginx.org$request_uri?;
}

Converting Mongrel rules

Typical Mongrel rules:

DocumentRoot /var/www/myapp.com/current/public

RewriteCond %{DOCUMENT_ROOT}/system/maintenance.html -f
RewriteCond %{SCRIPT_FILENAME} !maintenance.html
RewriteRule ^.*$ %{DOCUMENT_ROOT}/system/maintenance.html [L]

RewriteCond %{REQUEST_FILENAME} -f
RewriteRule ^(.*)$ $1 [QSA,L]

RewriteCond %{REQUEST_FILENAME}/index.html -f
RewriteRule ^(.*)$ $1/index.html [QSA,L]

RewriteCond %{REQUEST_FILENAME}.html -f
RewriteRule ^(.*)$ $1/index.html [QSA,L]

RewriteRule ^/(.*)$ balancer://mongrel_cluster%{REQUEST_URI} [P,QSA,L]

should be converted to

location / {
    root       /var/www/myapp.com/current/public;

    try_files  /system/maintenance.html
               $uri  $uri/index.html $uri.html
               @mongrel;
}

location @mongrel {
    proxy_pass  http://mongrel;
}