0

I'm trying to write my nginx conf with a rewrite pattern, but for now it only download me the file instead of run it with PHP.

My goal is to rewrite everything to the same file but with different query params:

# If file exist (like images, assets, etc...), just use it
http://foo.local/css/style.css => css/style.css
http://foo.local/images/img.png => images/img.png

# For all other:
http://foo.local/foo                   =>  web/index.php?module=foo
http://foo.local/foo/bar          =>  web/index.php?module=foo&action=bar
http://foo.local/foo/bar/baz  =>  web/index.php?module=foo&action=bar&params=baz
server {
    listen 80;
    server_name foo.local;

    root /var/www/foo;
    index index.php

    location / {
      try_files $uri $uri/ @rules;
    }

    location @rules {
      rewrite ^/([^/]*)$ /web/index.php?module=$1 break;
      rewrite ^/([^/]+)/([^/]+)/?$ /web/index.php?module=$1&action=$2 break;
      rewrite ^/([^/]+)/([^/]+)/([^/]+)/?$ /web/index.php?module=$1&action=$2&params=$3 break;
    }

    location /web/index\.php(/|$) {
        try_files $uri =404;
        fastcgi_pass  unix:/var/run/php/php7.4-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_buffer_size 128k;
        fastcgi_buffers 256 4k;
        fastcgi_busy_buffers_size 256k;
        fastcgi_temp_file_write_size 256k;
    }
}

When I go to http://foo.local/foo/bar/baz it just download me my index.php

Can you help me with that? Thank you

1

Try using rewrite ... last; instead of break; in your directives. last means that nginx starts a search for new location matching the changed URI, which means nginx should find your /web/index... location.

Furthermore:

location /web/index\.php(/|$)

doesn't likely do what you expect. A location block is a prefix match by default, so that location only matches

/web/index\.php(/|$)...

prefix literally, and anything with this prefix.

Most likely you wanted a regex match, which would be:

location ~ /web/index\.php(/|$)

Another option is to use correct prefix match:

location /web/index.php
1
  • Thanks ! I better understand what to do :) – Bouffe Jun 5 '20 at 6:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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