nginx + php-fpm. Redirect to php-script

2019-08-18 01:34发布

问题:

My nginx config part (successfully working)

... *config* ...

location ~ \.php$ {

    if (!-e $request_filename) {
        rewrite ^(.*)$ /index.php break;
    }
    set $nocache "";

    include fastcgi_params;
    fastcgi_pass  php-fpm;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/folder/$fastcgi_script_name;
    fastcgi_param DOCUMENT_ROOT /var/www/folder/;
    fastcgi_intercept_errors on;

    fastcgi_cache_use_stale error timeout invalid_header http_500;
    fastcgi_cache_key $host$request_uri;
    #   fastcgi_cache folder;
    fastcgi_cache_valid 200 1m;
    fastcgi_cache_bypass $nocache;
    fastcgi_no_cache $nocache;

    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 256k;
    fastcgi_busy_buffers_size 256k;

    proxy_connect_timeout   900;
    proxy_send_timeout  900;
    proxy_read_timeout  900;
    fastcgi_send_timeout    900;
    fastcgi_read_timeout 900;
}

Now I needed to add rewrite rule for /my/operation => /my.php?operation

location /my/ {
    rewrite ^(.*)$ /my.php?$1 break;
}

Rewrite rule is working, but php file is downloading, not executing.

I'm newbie in Nginx, so I need help

回答1:

Your problem is that by placing break you are telling nginx that you are done and you don't want any furtur processing to happen, so the location ~ \.php$ isn't proceessed, and thus the file is being downloaded.

By putting last instead you are telling nginx to do the rewrite and restart the processing again, this time it matches the location ~ \.php$ and thus the file is being processed.

So the final solution would be

location /my/ {
    rewrite ^(.*)$ /my.php?$1 last;
}

Though I usually tend to write it in a simpler way since you're going to match the whole thing

location /my/ {
    rewrite ^ /my.php?$1 last;
}

You can read the documentation to see all the flags and their meanings.



标签: nginx