【问题标题】:remove .php from url with rewrite rule使用重写规则从 url 中删除 .php
【发布时间】:2014-10-09 08:40:04
【问题描述】:

我想重写nginx中的url,这样.php扩展就可以省略了。

这就是我所拥有的,但这对我不起作用。有人知道怎么做吗?

谢谢。

  server {
        listen 80;
        server_name example.com;
        return 301 $scheme://www.example.com$request_uri;       
}

server {
        listen   80;
        root /usr/share/nginx/www;
        index index.php;
        server_name www.example.com;
        error_page 404 http://www.example.com/404.php;
        autoindex off;
        error_log  /usr/share/nginx/www/nginx_error.log  warn;

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

    location = / {
        rewrite ^ /index.php;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
    }

}

这是我的整个配置文件。

【问题讨论】:

    标签: php nginx


    【解决方案1】:

    花了一段时间试图让它正常工作。 php 文件和其他资产都在工作:

    location / {
    
        if (!-e $request_filename){
            rewrite ^(.*)$ /$1.php;
        }
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    【解决方案2】:

    @Makromat 我认为您在 cmets 中提到的 404 问题是您的 / 位置正在解析为 /.php 而没有文件名,因此为了解决它,我们可能会添加另一个位置来处理这种特殊情况

    location / {
        rewrite ^(.*)$ /$1.php;
    }
    location = / {
        rewrite ^ /index.php;
    }
    

    试试这个,告诉我它是否有效

    编辑:

    好吧,我有一个更好的主意,如果原始 URL 已经包含 .php 扩展名,则第一种情况将失败,因此最好将其定义为后备解决方案,试试这个

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

    尝试用你当前的 php 块替换它

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
    }
    

    【讨论】:

    • 您的第一个解决方案相对有效,但我没有任何 css 样式。重定向工作,但是当我单击菜单项之一(5 个项目中只有一个)时,立即下载了 php 文件,但其他四个菜单项工作正常:D 这真是太疯狂了。 (我喜欢 .htaccess)
    • 当我尝试您的第二个解决方案时...如果我点击任何菜单项我的浏览器下载 php 文件...
    • 配置中的 php 块是什么
    • 现在看我已经编辑了代码...这是我的整个配置文件非常感谢!!
    • 很抱歉打扰您,但现在仍然无法工作,请告诉我:500 内部服务器错误
    【解决方案3】:

    这样的东西应该是你正在寻找的东西。

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

    【讨论】:

    • 谢谢,但是当我重新启动 nginx 时出现错误:Restarting nginx: nginx: [emerg] unexpected "}" in /etc/nginx/sites-enabled/default:42 nginx: configuration file /etc/nginx/nginx.conf test failed
    • 糟糕,.php 后面的分号忘记了。
    • 非常感谢丹尼兹!!!现在它可以工作了,但我的主页显示错误 404...但菜单中的每个项目都是功能...仅/不工作...
    • 当我尝试添加到第一个服务器块主页时,我的后端工作正常。当我将此行添加到第二个服务器块时,主页和后端出现错误......当我尝试在两个块中添加 = 404 时......所以我不知道如何解决这个问题:/跨度>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-08
    • 2011-09-07
    • 2013-11-27
    • 2011-08-20
    • 1970-01-01
    • 1970-01-01
    • 2015-02-13
    相关资源
    最近更新 更多