nginx try_files 将 .html 重写为“干净”的 url

Cal*_*eng 8 nginx

这是包含静态 html 文件的目录

public
|-- index.html
|-- media
|   `-- blurred_image-8.jpg
|-- post
|   `-- 13considerations
|       `-- index.html
Run Code Online (Sandbox Code Playgroud)

我正在尝试配置 nginx 以转换所有.html以删除后缀结尾的 url 。

像这样:-

server {
    listen       80;
    server_name  mysite.com;

    location / {
        root   /var/www/mysite/public;
        try_files  $uri  $uri/ $uri/index.html;
    }

    location /media/ {
        alias /var/www/mysite/public/media/;
        error_page 404 = /404;
        expires 30d;
    }

    location /static/ {
        alias /var/www/mysite/public/static/;
        error_page 404 = /404;
        expires 30d;
    }
}
Run Code Online (Sandbox Code Playgroud)

这适用于主页“ http://mysite.com/ ”,但如果我尝试访问“ http://mysite.com/post/13thinkations/ ”,则会收到 500 内部服务器错误。

是什么赋予了?

pla*_*d87 17

您使用的示例适用于返回目录index.html文件的内容,但不适用于文件(例如,http://server/somedir/file不会返回 的内容/somedir/file.html)。

一个简化的配置,它将返回任何没有扩展名的 HTML 文件并将index.html用于目录,如下所示:

server {
    listen       80;
    server_name  mysite.com;

    index index.html;
    root /var/www/mysite/public;

    location / { 
        try_files $uri $uri/ @htmlext;
    }   

    location ~ \.html$ {
        try_files $uri =404;
    }   

    location @htmlext {
        rewrite ^(.*)$ $1.html last;
    }   
}
Run Code Online (Sandbox Code Playgroud)

这个怎么运作:

  • index index.html当访问目录 URI 时,指定将默认使用此文件。
  • 放在块root之外location将适用于服务器范围。
  • try_files $uri $uri/ @htmlext在最终尝试追加.html.
  • try_files $uri =404 是为了防止 Nginx 在找不到文件时陷入重写循环。
  • rewrite ^(.*)$ $1.html last追加.html并重新启动 URI 匹配过程。