User login

(If you're a human, don't change the following field)
Your first name.

Nginx URL rewrites... the correct method

Last night I was looking for the best way to impliment clean urls on a Drupal install in a sub-directory; naturaly I found the following code

location / {
    root   /path/to/drupal;
    index  index.php index.html;

    if (!-f $request_filename) {
        rewrite  ^(.*)$  /index.php?q=$1  last;
        break;
    }

    if (!-d $request_filename) {
        rewrite  ^(.*)$  /index.php?q=$1  last;
        break;
    }
}

Which is incorrect and apparently evil too. The correct method is to use the "try_files" setting in your Nginx config.

location / {
    root   /path/to/drupal;
    index  index.php index.html;

    try_files $uri $uri/ @rewrite;
}

location @rewrite {
        rewrite ^/(.*)$ /index.php?q=$1;
}

The first $uri checks for the file using the path provided eg. /path/to/file.name. The second $uri/ works exactly the same way but add a forward slash, this is needed to make the index setting work correctly. And lastly is @rewrite which calls the @rewrite location.

To make this config work in a sub-directory the root location and index.php path need to be changed.

location /path/to/sub/dir/ {
    root   /path/to/drupal;
    index  index.php index.html;

    try_files $uri $uri/ @rewrite;
}

location @rewrite {
        rewrite ^/(.*)$ /path/to/sub/dir/index.php?q=$1;
}

Post new comment

(If you're a human, don't change the following field)
Your first name.
The content of this field is kept private and will not be shown publicly. If you have a Gravatar account associated with the e-mail address you provide, it will be used to display your avatar.
  • Allowed HTML tags: <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd>
  • Syntax highlight code surrounded by the <pre class="brush: lang">...</pre> tags, where lang is one of the following language brushes: bash, cpp, css, jscript, perl, php, plain, python, ruby, sass, sql.
  • Lines and paragraphs break automatically.
  • Each email address will be obfuscated in a human readable fashion or (if JavaScript is enabled) replaced with a spamproof clickable link.

More information about formatting options

Designed by Richard Banks Hosted by DataPoint Powered by Drupal
Creative Commons License
Copyright © 2005-2017 Richard Banks.
Some rights reserved.