How to remove both .php and .html extensions from

2019-01-03 02:42发布

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

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

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.

Any advices?

标签: php html nginx
4条回答
霸刀☆藐视天下
2楼-- · 2019-01-03 03:16

To further Mohammad's answer, you might also want to offer redirects from .html and .php to the extensionless versions.

This can be accomplished due to the fact that $request_uri contains "full original request URI (with arguments)", and is not affected by the internal rewrites that are not visible to the user.

server {
  index index.html index.php;
  location / {
    if ($request_uri ~ ^/(.*)\.html$) {  return 302 /$1;  }
    try_files $uri $uri/ $uri.html $uri.php?$args;
  }
  location ~ \.php$ {
    if ($request_uri ~ ^/([^?]*)\.php($|\?)) {  return 302 /$1?$args;  }
    try_files $uri =404;
    # add fastcgi_pass line here, depending if you use socket or port
  }
}
查看更多
Rolldiameter
3楼-- · 2019-01-03 03:17

Perhaps this may be of use for you... It' Simple and gets the job done:

location / {
  rewrite ^/([^\.]+)$ /$1.html break;
}
查看更多
再贱就再见
4楼-- · 2019-01-03 03:20

No need for extra blocks and named locations and everything. Also move the index line outside the location block

server {
  index index.html index.php;
  location / {
    try_files $uri $uri/ $uri.html $uri.php$is_args$query_string;
  }
  location ~ \.php$ {
    try_files $uri =404;
    # add fastcgi_pass line here, depending if you use socket or port
  }
}

Keep in mind that if you have a folder and a file with the same name inside the same folder, like /folder/xyz/ and /folder/xyz.php you won't be able to run the php file if the folder xyz contains an index.php or index.html, just keep this in mind.

查看更多
虎瘦雄心在
5楼-- · 2019-01-03 03:40

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

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

查看更多
登录 后发表回答