Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have following nginx configuration:

  location / {
      try_files $uri $uri/ index.html =404;

      if (!-e $request_filename) {
        rewrite ^/(.+)$ index.php?url=$1 last;

 location ~ .php$ {
    # protection from known vulnerability
    fastcgi_split_path_info ^(.+\.php)(/.+)$;
    include fastcgi_params;
    fastcgi_pass   unix:/var/run/php5-fpm.sock;
    fastcgi_index  index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

(fastcgi_params are defaults from Debian package)

it works for request /, however when the request is rewritten the main file is not found:

request is /contact which should be rewritten to /index.php?url=contact

 *104 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client:, server: localhost, request: "GET /contact HTTP/1.0", upstream: "fastcgi://unix:/var/run/php5-fpm.sock:", host: "localhost:8080"

I'm unable to get from logs what is actuall fastcgi trying to load, which path?

share|improve this question
Please post the entire server block. – Michael Hampton Apr 10 '14 at 12:52
up vote 4 down vote accepted

Note that index.php and /index.php are different URIs. You've forgotten slashes in your rewrites.

share|improve this answer

This is a better way to implement the same functionality:

location / {
    try_files $uri $uri/ @rewrite;

location @rewrite {
    rewrite ^/(.+)$ /index.php?url=$1 last;

and then your PHP location block as in your setup.

try_files checks first if the file matching $uri exists, then a directory, and if neither exists, it uses the rewrite -location, which runs the script.

Most likely reason your setup was not working was the missing / from the rewrite script path. Anyway, this setup is simpler is the preferred one with nginx.

share|improve this answer
why not try_files $uri $uri/ /index.php?url=$uri; ? – Alexey Ten Apr 10 '14 at 12:23
Very good point, I have never even thought like that. Short and beautiful! – Tero Kilkanen Apr 10 '14 at 16:16

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.