使用重写规则从网址中删除.php [英] remove .php from url with rewrite rule

查看:54
本文介绍了使用重写规则从网址中删除.php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用nginx重写url,以便可以省略.php扩展名.

I want to rewrite the url in nginx so that the .php extension can be omitted.

这是我所拥有的,但是对我来说不起作用.有人知道如何执行此操作吗?

This is what I have, but this isn't working for me. Anyone any idea how to do this?

谢谢.

  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;
    }

}

这是我的整个配置文件.

this is my whole config file.

推荐答案

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

@Makromat I think the 404 issue you are mentioning in the comments is that your / location is resolving to /.php without a file name, so to solve it we might add another location just to handle this special case

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

尝试一下,告诉我是否可行

Try this and tell me if it works

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

Ok scratch that, I have a better idea, the first case will fail if the original URL already contains the .php extension so it's better to define it as a fall back solution, try this

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

尝试用您当前的php块替换

Try replace this with your current php block

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

这篇关于使用重写规则从网址中删除.php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆