如何使用 NGINX 从 url 中删除 .php 和 .html 扩展名?

问题描述:

我希望我的 nginx make 显示所有 url 的干净.

I want my nginx make display all url's clean.

  • http://www.mydomain.com/indexhtml.html as http://www.mydomain.com/indexhtml
  • http://www.mydomain.com/indexphp.php as http://www.mydomain.com/indexphp

通过一些研究,我使第一个案例奏效.它通过以下配置完成:

With some research I've made the first case to work. It`s done by following configuration:

location / {
    root   html;
    index  index.html index.htm index.php;
    try_files $uri.html $uri/ =404; 
}

它适用于 indexhtml.html 显示为 indexhtml,但 .php 没有任何反应.如果我将 $uri.html 更改为 $uri.php,它既不适用于 .html,也不适用于 .php.我尝试在 php 位置放置类似的东西,但没有成功.

It works for indexhtml.html displaying as indexhtml, but nothing happens with .php. If I change $uri.html to $uri.php, it works neither for .html, neither .php. I`ve tried to put something similar in php location but without any success.

有什么建议吗?

根据我的研究,如果您将/etc/nginx/conf.d/domain.tld.conf 文件附加到包括:

From what I've researched, if you append your /etc/nginx/conf.d/domain.tld.conf file to include:

location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
    index index.html index.htm index.php;
}

location ~ .php$ {
    try_files $uri =404;
}

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

然后重启nginx并试一试.希望这会帮助你!可以找到更多信息(在我找到的地方)这里@tweaktalk.net一个>

Then restart nginx and give it a go. Hopefully this will help you! More information can be found (where I found it) here @ tweaktalk.net