[教程] WordPress修改permalink后页面出现 nginx 404问题

只需修改 Nginx 配置文件,即可完美解决

在安装好 WordPress 后,如果修改 Permalink 结构,有可能会导致网站除首页外的其他页面出现 nginx 404 问题,同时,也可能会无法保存文章草稿,发布文章。

本文将大致介绍 Permalink 的相关知识及该问题的一种解决方法。

Permalink

Permalinks are the permanent URLs to your individual weblog posts, as well as categories and other lists of weblog postings. A permalink is what another weblogger will use to link to your article (or section), or how you might send a link to your story in an e-mail message. The URL to each post should be permanent, and never change — hence permalink.

Permalink(永久链接)是一个互联网术语,通常用于指代网页、博客文章或其他在线内容的固定、永久的URL(统一资源定位符)。永久链接是一个指向特定页面或资源的网址,其特点是在内容不变的情况下保持不变。这有助于确保用户可以随时访问特定的内容,而不必担心链接会因内容更新而失效。

永久链接通常用于博客、新闻网站和其他内容管理系统中,以便读者和搜索引擎可以轻松地找到和访问特定的文章或页面。每篇博客文章或页面都有一个唯一的永久链接,它可以包含文章的标题、日期、类别和其他相关信息,以便更好地描述内容。

永久链接对于网站的用户友好性和搜索引擎优化(SEO)非常重要,因为它们使用户能够轻松地分享和书签页面,并且有助于搜索引擎了解页面的内容和结构。此外,永久链接还可以帮助网站维护更好的链接一致性,以防止404错误或失效的链接。因此,在创建和管理网站或博客时,合理设置和管理永久链接是一项重要的任务。

WordPress 安装后之后,默认的 Permalink 结构为 Plain,e.g.

https://zblogs.top/?p=123

Plain 结构的 Permalink 中出现的数字 123, 是 WordPress 为这篇文章特定生成的 ID,它指的是网站数据库中的第 123 篇文章。

虽然 Google 仍然理解这个页面上的内容,但这种格式的 URL 看起来并不专业,对网站的 SEO 也没有任何帮助,因为这个 URL 没有描述页面提供的是什么内容,也不便于链接的分享和传播。

为了让 Permalink 对搜索引擎和读者更加友好,我们会选择 Post name 的结构:

https://zengbin.tech/ubuntu-nginx-php-mysql-build-wordpress-site/

如果是新闻网站,那 Permalink 可以选择 Day and name 的结构(传达文章时效性):

https://zengbin.tech/2022/01/16/sample-post/

简言之,建议使用简单明了的 Permalink 结构,对大多数网站来说,将文章标题信息附加到 Permalink 中是有意义的,因此推荐使用 Post name 的结构。

如何解决修改 permalink 后页面 Nginx 404问题

使用 WordPress 默认的 Plain Permalink 结构,并不会遇到网页 Nginx 404 的问题;在修改 Permalink 结构之后,如果遇到页面出现 Nginx 404 问题,通常情况下修改 Nginx 配置文件就可以解决:

在网站 Nginx 配置文件中,在 server {},添加(或修改)如下代码:

location / {
            try_files $uri $uri/ /index.php?$args;
}

完整 server {} 部分代码如下:

server {
        root /var/www/wordpress;
        server_name example.com;
        location / {
                    try_files $uri $uri/ /index.php?$args;
        }
        location ~ \.php$ {
                include snippets/fastcgi-php.conf;
                fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;
        }
}

参考文档:

Using Permalinks: https://wordpress.org/support/article/using-permalinks/#using-pretty-permalinks


Image by jcomp on Freepik

More Reading

Post navigation

Leave a Comment

Leave a Reply

Your email address will not be published. Required fields are marked *