How to get rid of app.php in Symfony2 URIs with Ng

2019-08-10 09:33发布

问题:

I'm trying to get a clear understanding of what's going on with my nginx configuration file for Symfony2, here it is:

    server {
        listen 80;
        autoindex on;
        server_name example.com;
        root /var/www/example.com/web;

        rewrite ^/app\.php/?(.*)$ /$1 permanent;

        location / {
            index app.php;
            try_files $uri $uri/ @symfony;
        }

        location @symfony {
            rewrite ^(.*)$ /app.php/$1 last;
        }

        location ~ ^/app\.php(/|$) {
            include fastcgi_params;
            fastcgi_pass unix:/var/run/php5-fpm.sock;
            fastcgi_split_path_info ^(.+\.php)(/.*)$;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param SCRIPT_NAME $fastcgi_script_name;
        }
}

In short, I'm trying to strip app.php in every possible URI that a user can set e.g. example.com/app.php/demo or just example.com/app.php.

This config actually works for URIs like ones above, but it leads to a redirect loop in case of trying to access "root" URI example.com.

And if I remove $uri/ from try_files and leave only $uri and a fallback @symfony there, everything is working fine except I can't access any directories as they're going to be processed by SF.

I'm out of ideas, did a lot of research on how nginx and rewrites actually work, but as for now it's a dead end for me. If you can find a solution to stay with $uri/ in try_files and get out of a loop at front, please let me know.

回答1:

This solution from Nginx Tips worked for me. It's almost, but not quite, the same as yours.

server {
server_name domain.tld www.domain.tld;
root /var/www/project/web;

location / {
# try to serve file directly, fallback to rewrite
try_files $uri @rewriteapp;
}

location @rewriteapp {
# rewrite all to app.php
rewrite ^(.*)$ /app.php/$1 last;
}

location ~ ^/(app|app_dev|config).php(/|$) {
fastcgi_pass unix:/var/run/php5-fpm.sock;
fastcgi_split_path_info ^(.+.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param HTTPS off;
}

error_log /var/log/nginx/project_error.log;
}