Nginx – How to tell Nginx to not rewrite URL’s in selected location

nginxPHPrewriteurl

I am writing some PHP CMS code with a clean url implementation in Nginx. To improve security of my code I want to rewrite all of the requests in my root directory / using the following type:

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

With this kind of rewrite the rest of the php scripts will not be accessible from the user's side (they will be only, if included in php, am I right?). However, I do not want to rewrite the request in one location (for mi that will me /static/), because I will be serving only static content such as images and css from that location. How can I make this rewrite not work in certain locations?

Best Answer

Understanding and using the location directive should solve your problem. When location is followed only by a prefix string (i.e. without modifiers such as '=', or '~*'), the longest prefix string is matched first. For example:

server {
    server_name example.org;
    root /var/www/site;

    location / {
        # Configuration A
    }

    location /static {
        # Configuration B
    }

In this configuration, the URL example.org/static/foo.gif would match Configuration B because the prefix string /static is longer than /. Meanwhile, example.org/index.php?q=bar would match Configuration A because that is the only match.

You could then have Configuration A serve up content with PHP, while Configuration B serves static content.

Also, I would highly recommend reading through the Nginx Pitfalls page, if you haven't already. It addresses some issues that are highly relevant in your situation, such as taxing rewrites, using fastcgi_pass safely, and so forth.

Related Topic