duanqiang5722 2013-11-14 10:27
浏览 61
已采纳

使用重写规则从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?

Thanks.

  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.

  • 写回答

3条回答 默认 最新

  • dousi1994 2013-11-14 12:47
    关注

    @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

    EDIT:

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

    Try replace this with your current php block

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 关于大棚监测的pcb板设计
  • ¥15 stm32开发clion时遇到的编译问题
  • ¥15 lna设计 源简并电感型共源放大器
  • ¥15 如何用Labview在myRIO上做LCD显示?(语言-开发语言)
  • ¥15 Vue3地图和异步函数使用