【问题标题】:How to redirect and remove the .html extension from a URL?如何从 URL 中重定向和删除 .html 扩展名?
【发布时间】:2013-09-26 06:12:45
【问题描述】:

在 nginx 上配置一些重写规则时,我正在为此烦恼。我在 Debian Wheezy 机器上运行 nginx 1.2.1。

考虑以下树:

/
├── index.html
├── folder/
│   └── index.html
└── file.html

我希望这些文件由 nginx 提供服务,这样就无需在 URL 中指定任何 .html,并且对 folder/index.html 的任何调用都将重写为 folder/,对 @ 的任何调用987654325@改写成index

这是此描述的正式版本。请求示例在左侧,我尝试获取的相应响应在右侧(HTTP 代码 301 + 重定向位置或 HTTP 代码 200 + 要显示的文件):

1. http://example.com/                  -> 200 (/index.html)
2. http://example.com/index.html        -> 301 http://example.com/
3. http://example.com/index             -> 301 http://example.com/

4. http://example.com/file              -> 200 (/file.html)
5. http://example.com/file.html         -> 301 http://example.com/file

6. http://example.com/folder/           -> 200 (/folder/index.html)
7. http://example.com/folder            -> 301 http://example.com/folder/
8. http://example.com/folder/index.html -> 301 http://example.com/folder/
9. http://example.com/folder/index      -> 301 http://example.com/folder/

10. http://example.com/foobar           -> 404

到目前为止,我最接近的尝试是/etc/nginx/sites-enabled/example.com的以下配置:

server {
    server_name example.com;
    root /var/www/example.com/public_html;

    rewrite ^(.*/)index(\.html)*$ $1 permanent;        # Applies to 2, 3, 8, 9
    rewrite ^(/.+)\.html$ $1 permanent;                # Applies to 5

    try_files $uri $uri.html "${uri}index.html" =404;  # Handles 1, 4, 6, 10
}

如您所见,案例7 丢失。现在,我得到了:

7'. http://example.com/folder           -> 404

我也设法拥有:

7''. http://example.com/folder          -> 200 (/folder/index.html)

但这绝对是我不希望 SEO 明智的事情(除其他外),因为 2 个不同的 URL(带和不带斜杠)返回相同的内容。

每个配置都没有通过我所有的测试用例。

请注意,当我简单地禁用 2 rewrites 和 try_files7 按预期应用(以及 1610 而不是其他的)时,重定向默认有效。我不明白这个重定向规则是如何以及在哪里出现的,所以这里是我的正式问题:我怎样才能让这个重定向重新出现,进而,我怎样才能让我的 10 个测试用例正常工作?

非常感谢,我是认真的:)

PS:我尽我所能,当然如果有什么不清楚的地方,不要犹豫,要求澄清!

【问题讨论】:

    标签: redirect url-rewriting nginx


    【解决方案1】:

    您做错了几件事,首先您不会进行任何 301 重定向,如果您正在访问某些内容,则使用重定向,但随后您希望它转到其他内容,例如,如果我们正在执行升级。

    http://example.com/index.html =>redirects to=> http://example.com/maintenance.html
    

    你需要的是将某些东西的格式更改为其他东西,顺便交换你的重写,重写像这样工作

    rewrite [what to match] [what to do with it]
    

    你的重写是说当我得到一个指向 /index.html 的 URL 时,它会重定向到 /index,然后会给你一个 404,因为你没有一个名为 /index 的真实文件

    我想和try_files一起做

    server {
        server_name example.com www.example.com;
        root /my/root/path;
        location / {
            try_files $uri $uri/ $uri.html;
        }
    

    试试这个,告诉我结果如何。

    【讨论】:

    • try_files 指令确实在文件系统上寻找文件,因此/page 将加载/page.html,但没有rewrite 指令,/page.html 不会重定向按预期发送至/page。两个 URL 都会响应。另外,我不明白你为什么说我的rewrites 被交换了,因为他们满足了你的要求。
    猜你喜欢
    • 1970-01-01
    • 2015-03-20
    • 1970-01-01
    • 2022-03-04
    • 2023-02-19
    • 1970-01-01
    • 2017-02-27
    • 2017-03-02
    • 1970-01-01
    相关资源
    最近更新 更多