You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多
文档控制台
免费开始使用

Nginx优化:消除尾部斜杠重定向,保障SEO友好

Fixing SEO-Unfriendly Trailing Slash Redirects in Nginx

Hey there, I see you're dealing with a redirect that's tough on SEO: http://localhost/blog is getting automatically redirected to http://localhost/blog/. This sort of redirect splits page authority and can hurt your search rankings, so it’s great you’re addressing it.

The Fix That Works

Adding the try_files $uri $uri/index.html =404; directive to your location block resolves this issue perfectly. This tells Nginx to first serve the exact URL you requested (without the trailing slash), and if that doesn’t exist, it’ll look for an index.html file in the corresponding directory. No more unwanted redirects—both URLs will return a 200 status code as you wanted.

Fully Tested Working Configuration

Here’s the complete, validated config that fixes the redirect issue while keeping your existing cache settings. It’s also been tested to work smoothly with HTTP-to-HTTPS redirect scenarios:

server {
    listen 80 default_server;
    server_name localhost;
    server_name_in_redirect on;
    location / {
        add_header Cache-Control "public";
        expires 1y;
        try_files $uri $uri/index.html =404;
        root /work/front-page/dist/browser;
    }
}

Why This Works

Nginx’s default behavior is to redirect directory requests without a trailing slash to the version with one. The try_files directive overrides this, letting both the trailing-slash and non-trailing-slash versions of your URL serve content directly. This is ideal for SEO, and it also plays nicely with single-page applications (SPAs) that use client-side routing.

内容的提问来源于stack exchange,提问作者Borislav Stoilov

火山引擎 最新活动