【问题标题】:nginx rewrite html file and add trailing slashnginx重写html文件并添加斜杠
【发布时间】:2017-05-27 21:08:03
【问题描述】:

我已经阅读了十几个复习题。大多数问题都是针对 .php 的,但我有简单的 .html 文件,所以 about => about.html 。但我无法让 nginx 做到这一点:

  • 接受带有或不带有“/”的网址
  • 将 domain.com/about 和 domain.com/about/ 重定向到 domain.com/about.html
  • 在 URL 中添加斜杠,这样如果我写 domain.com/about 它就会写 domain.com/about/

我已尝试使用此代码 rewrite ^/([a-zA-Z0-9]+)$ /$1.html; 但它在以“/”结尾的 url 上给了我 404 错误。也试过这个 rewrite ^([a-zA-Z0-9]+)/?$ $1.html 有同样的错误。

有人建议我应该使用 try try_files?

我也试过这个,它给出了 500 错误:

location / { 
rewrite ^(.*)$ /%1 redirect; 
rewrite ^/([^\.]+)$ /$1.html break; 
}

我尝试将 apache 从建议 here 转换为 nginx (winginx.com),但没有成功。

此代码不起作用。我正在尝试重定向并添加斜杠:

if (!-e $request_filename){
rewrite ^/(.*)/$ /$1 redirect;
}
if (!-e $request_filename){
rewrite ^/(.*[^/])$ /$1/ redirect;
}

任何建议都会让我高兴。

【问题讨论】:

  • 最简单的解决方案是将about.html 重命名为about/index.html 然后nginx 的索引模块几乎可以满足您的需求。
  • 这听起来有点矫枉过正。我必须为每个 html 文件创建一个文件夹,而不是单个 html 文件,并将 index.html 文件中的内容放入该文件夹中?!?

标签: .htaccess nginx url-rewriting


【解决方案1】:

我已经测试了此配置,它似乎满足您的要求 (YMMV):

root /path/to/root;

location / {
    try_files $uri @rewrite;
}
location @rewrite {
    rewrite ^(.*[^/])$ $1/ permanent;
    rewrite ^(.*)/$ $1.html break;
}

第一个位置尝试按原样提供资源文件所必需的文件。否则,它会按照指定的位置进行。

指定位置将永久重定向任何不以/ 结尾的URI。否则,将提供 .html 文件。

详情请参阅this documentthis document

【讨论】:

  • 嗨,对不起,这不起作用。有了这个配置,我在 index.html (根)上得到一个 404 页面。当我点击例如“projects”它显示projects.html,URL是“example.com/projects”,但是所有的css和图像都被破坏了。在页面项目上,我单击链接 "about" (页面是 about.html),我得到“example.com/projects/about” -> 它应该是“example.com/about " 并从那里转到 "example.com/projects/about/about/about ...." 等,所以有一个内部循环。
  • 使用路径相关资源(css & js)将不适用于您的方案,因为浏览器假定尾随 / 是一个子目录。指向about.html 的链接可能应该是/about.html,以避免出于同样的原因获得/project/about.html。我不明白内部循环 - 但这些类型的方案存在很大风险。
  • 我同意理查德的风险!我重写了绝对路径,并且 css 和图像正在工作。也使链接绝对。这修复了错误的 URL。感谢您的洞察力和理解我要解决的问题!
【解决方案2】:

我认为 try_files 在这里是合适的。例如:

location /about {
    try_files about.html;
}

【讨论】:

  • 适用于 about.html,但我有很多文件,about.html、contact.html、projects.html、gallery.html 等...
  • 您可以为每个块创建一个块或使用正则表达式,例如:location ~ ^/(.*)/?$ {try_files $1.html;}
猜你喜欢
  • 2015-01-27
  • 1970-01-01
  • 2021-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-27
相关资源
最近更新 更多