关注Java领域相关技术 记录有趣的事情

WordPress自定义链接取消index.php后Nginx报404解决办法

US-B.Ralph
US-B.Ralph
2016-05-012016-05-03

故障现象

默认情况下 WordPress 中采用自定义地址时,地址中包含 index.php 内容使得地址变为:
https://www.us-b.fun/index.php/%var1%/%var2%/%va3r%/%var4%/%var5%/%var5%.html
本来也没什么就是看起来不爽,所以就尝试把index.php去掉,可是去掉之后发现文章404了:

寻找答案

  1. 再次返回WordPress的后台options-permalink设置中,发现WordPress很贴心的提供了Nginx配置文档
  2. Nginx配置文档中发现有一节是介绍Nginx关于WordPress的规则:General WordPress rules,在这里我们找到了答案:
# WordPress single site rules.
# Designed to be included in any server {} block.
# Upstream to abstract backend connection(s) for php
upstream php {
        server unix:/tmp/php-cgi.socket;
        server 127.0.0.1:9000;
} 
server {
        ## Your website name goes here.
        server_name domain.tld;
        ## Your only path reference.
        root /var/www/wordpress;
        ## This should be in your http block and if it is, it's not needed here.
        index index.php;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }

        location / {
                # This is cool because no php is touched for static content.
                # include the "?args" part so non-default permalinks doesn't break when using query string
                try_filesuri uri/ /index.php?args;
        }

        location ~ \.php{
                #NOTE: You should have "cgi.fix_pathinfo = 0;" in php.ini
                include fastcgi.conf;
                fastcgi_intercept_errors on;
                fastcgi_pass php;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico) {
                expires max;
                log_not_found off;
        }
}
  1. 可以看到 location / 这里有一行 try_files uriuri/ /index.php?$args; 就是用来去除 *.php 以及 ?args
location / {
    # This is cool because no php is touched for static content.
    # include the "?args" part so non-default permalinks doesn't break when using query string
    try_filesuri uri/ /index.php?args;
        }
  1. 配置我们自己的deomain_Nginx.conf文件,重启Nginx即可

Nginx官方提供了更多关于WordPress配置的例子,点此查看

US-B.Ralph
建站记录

One Comment

  • wp

    楼主思路清晰,解决了我的问题。

Leave a Comment

邮箱地址不会被公开。 必填项已用*标注

11 + 9 =