nginx:url 重写不起作用

nginx:url 重写不起作用

我使用 Jelastic 和 nginx 1.6.1,并希望使用不带 .php 扩展名的友好 URL。因此,如果有人访问例如https://domain.com/faq.phpnginx 应该将其重写为https://domain.com/faq并显示内容。

我花了几个小时尝试了以下解决方案来实现这一点:

location / {
    try_files $uri $uri.php $uri/;
}

但没有成功,当我尝试访问 domain.com/faq 时总是出现 404 错误

有人有可行的解决方案吗?这是我的默认 nginx.conf 文件:

worker_processes  1;
error_log /var/log/nginx/error.log;

events {
    worker_connections 1024;
}


http {

    server_tokens off;
    include mime.types;
    default_type application/octet-stream;

    log_format  main  '$http_x_forwarded_for - $remote_user [$time_local] "$request" '
        '$status $body_bytes_sent "$http_referer" '
        '"$http_user_agent" "$http_x_forwarded_for"';

    access_log /var/log/nginx/access.log  main;
    sendfile on;
    keepalive_timeout 65;

    server {

        listen 80;
        server_name localhost;
        include /etc/nginx/aliases.conf;
        index index.php index.html index.htm;
        error_page 500 502 503 504  /50x.html;

        location / {
            root /var/www/webroot/ROOT;
            index index.html index.htm index.php;

            location ~ \.php$ {
                location ~ /\. { deny all; access_log off; log_not_found off; }
                include /etc/nginx/fastcgi_params;
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_param SCRIPT_FILENAME /var/www/webroot/ROOT$fastcgi_script_name;
                fastcgi_param PATH_INFO $fastcgi_script_name;
                fastcgi_param DOCUMENT_ROOT /var/www/webroot/ROOT;
            }

        }

        location = /50x.html {
            root   html;
        }

        location ~ \.php$ {
            location ~ /\. { deny all; access_log off; log_not_found off; }
            include /etc/nginx/fastcgi_params;
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME /var/www/webroot$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_script_name;
            fastcgi_param DOCUMENT_ROOT /var/www/webroot;
        }

        include /etc/nginx/conf.d/*.conf;

    }
}

答案1

我知道您想将 faq 重写为 faq.php,如果是这样,您需要做的就是:

rewrite ^/faq$ faq.php last;

就是这样。

相关内容