【问题标题】:Nginx rewrite: Redirect .php files to it's related rewritten url?Nginx 重写:将 .php 文件重定向到相关的重写 url?
【发布时间】:2020-04-08 20:34:55
【问题描述】:

我有 nginx 重写配置如下:

location ~ \.php$ {
    try_files $uri /index.php =404;
    fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

location / { 
    try_files $uri $uri.php $uri/ =404;
    rewrite ^/about/$ /about.php;
}

/about/ 这个 url 工作正常,并显示 about.php 文件的内容。

但我希望当有人尝试直接访问 about.php 时,他们应该得到 /about/,或者如果相关文件 url 重写不存在,那么他们应该得到 404。

请帮助我如何做到这一点?

【问题讨论】:

    标签: php nginx url-rewriting nginx-location


    【解决方案1】:

    这可能对你有用。

    location /about {
    try_files $uri $uri $uri/ @extensionless-php;
    }
    
    location @extensionless-php {
    rewrite ^(.*)$ $1.php last;
    }
    

    参考:https://www.digitalocean.com/community/questions/how-to-remove-php-using-nginx

    【讨论】:

    • 嗨@Nabeel,我已经检查过了,但是当我尝试访问example.com/about.php 时它不起作用,它仍然显示about.php 页面。不重定向到 /about/ url。
    • 你好,@Parshant,如果这对你不起作用,那么你最好改变方法来解决这个问题。您的 index.php 应该是动态的,并且应该能够根据请求包含相关文件。例如,如果没有 URL 重写,您的页面应该可以像 example.com/index.php?page=about 一样访问 使用 URL 重写,您的页面应该像 example.com/about 一样可以访问删除“rewrite ^/about/$ /about.php;”来自 nginx 配置
    猜你喜欢
    • 2013-01-12
    • 2013-10-08
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-20
    相关资源
    最近更新 更多