WordPress ошибка 404 nginx

Tested with

  • Nginx 1.19.0
  • WordPress 5.4
  • PHP 7.2.24
  • Vesta CP

After switched to Nginx from Apache server WordPress started showing 404 or Page not found errors. Homepage loads but all permalinks are 404 when using Nginx & PHP-FPM

What causes the Nginx wordpress permalinks 404 error

WordPress recommends PHP-FPM as the PHP handler to take advantage of NGINX. Unfortunately, mod_security rules will not work with NGINX, and .htaccess rewrite rules and restrictions will no longer apply. Nginx and Apache rewrite rules have a totally different format. This means that WordPress permalink rewrites will no longer work after switching the webserver.

Similarly, modifying the Nginx configuration also helps in solving the WordPress permalinks 404 error. Here, within the per domain Nginx configuration file for the domain. Edit both nginx.conf and nginx.ssl.conf files to make it work on http:// and https://

  • /home/admin/conf/web/domain-name.nginx.conf
  • /home/admin/conf/web/domain-name.nginx.ssl.conf

edit the following location block within the server block:

cd /home/admin/conf/web/
vim domain-name.nginx.ssl.conf
// vim domain-name.nginx.conf
// press i to enter vim insert mode
//add try_files $uri $uri/ /index.php?$args; under location / {} block
location / {
    # file ($uri) or directory ($uri/)? if not, redirect to /index.php + query string
    try_files $uri $uri/ /index.php?$args;
    index  index.html index.htm index.php;
}
// press ESC to exit from vim insert mode
:wq // save and quit configuration file

For more Vim editor command read this post Basic Vim Commands to start work with Vim Editor

Here is another solution, you can try this if the previous one is not working for you. I have tested both on my Linode server and both worked perfectly.

location / {
    rewrite ^/(.*)$ /index.php?$1;
    index  index.html index.htm index.php;
}

Further, we reload the Nginx configuration for the changes to take effect.

Nginx make sites faster. It definitely has an upper edge in serving static content. That’s why, many WordPress users switch to Nginx.

Often, this switch cause Nginx WordPress permalinks 404 errors. This happens as Apache’s rewrite rules do not work with NGINX.

Therefore, fixing WordPress websites is one of the common task that we do as part of our Server Administration Services.

Today, we’ll see how Bobcares’ Engineers fixed Nginx WordPress permalinks 404 error for one of our customer.

Details of WordPress permalinks 404 error

We’ll begin with seeing the details of the error reported by the customer. The Help-desk request said:

In my domain, only the home page is working, where as every other page returns a 404 not found error. I
think this is either due to .htaccess file, permalink settings, or Nginx Configuration? Please fix!

The customer had website hosted on a Plesk server. He recently switched to Nginx from Apache. That’s when he started getting 404 or Page not found errors.

What causes permalinks 404 error in Nginx?

WordPress come with the option to create permanent links to blog posts on the website.  And, the links can be created based on post name, post number, date, etc.

Now, its time to see what causes the Nginx wordpress permalinks 404 error.

Basically, customer choose PHP-FPM as the PHP handler, as it is the handler that WordPress recommends. And, to take advantage of NGINX, we recommend customers to enable PHP-FPM on all domains that serve PHP content.

Unfortunately, mod_security rules will not work with NGINX, and .htaccess rewrite rules and restrictions will no longer apply. Nginx and Apache rewrite rules have totally different format. The directives in Apache like Rewritecond, RewriteRule, etc. take its equivalents in Nginx configuration.

This means that WordPress permalink rewrites will no longer work after switching the web server.

Steps for fixing Nginx wordpress permalinks 404 error

Luckily, there are several methods to fix the WordPress permalinks on Nginx. Let’s take a look at each of them.

1. Converting rewrite rules to Nginx format

A quicker method to fix the permalink error is to convert the Apache rewrite rules to Nginx format. Either we can manually rewrite the rules or use various plugins for automatic conversion.

For example, in servers with Plesk control panel, there comes an extension like “htaccess to nginx“. By using this extension, it would rewrite the custom Apache directives according to the rules of nginx syntax. The plugin details are as shown below.

We just had to add the rules in the Additional Nginx directives section inside the domain settings as shown below.

That fixed the permalinks and the website started working again.

2. Modifying Nginx configuration

Similarly, modifying the Nginx configuration also helps in solving the WordPress permalinks 404 error. Here, within the per domain Nginx configuration file for the domain, our Support Engineers edit the following location block within the server block:

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

Further, we reload the Nginx configuration for the changes to take effect.

3. Tweaking Proxy mode

Similarly in Plesk servers having Apache with Nginx as reverse proxy, tweaking domain’s setting also solve the permalink errors. The .htaccess is ignored if Apache is turned off for the domain. And, it results in Permalink 404 errors.

Therefore, in some cases, to solve the error, we turn ON the option Proxy mode from Plesk > Domains > example.com > Apache & nginx Settings.

[Finding Nginx WordPress permalinks 404 error trouble? We can fix your website.]

Conclusion

To be precise, Nginx wordpress permalinks 404 error occurs when the rewrite rules do not follow the Nginx format. The fix involves converting the rules, modifying Nginx configuration and many more. Today, we saw how our Support Engineers solved the error for our customer and made permalinks working again.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Как настроить Nginx так, чтобы посты и страницы при включённых ЧПУ открывались корректно.

В WordPress можно использовать человеко-понятные url (ЧПУ), чтобы из адреса страниц и людям, и поисковым системам сразу становилось понятно, о чём содержимое. Например, взглянув на tx8.ru/kak-podruzhit-tt-rss-i-fail2ban/, видно, что на странице информация про настройку fail2ban. ЧПУ включаются в админке сайта, раздел «Настройки постоянных ссылок».

Настройки постоянных ссылок в WordPress

Настройки постоянных ссылок в WordPress

Так вот, любой режим именования ссылок, кроме простого (простой — это не ЧПУ), в стандартной конфигурации веб-сервера Nginx не работает. Все страницы, кроме главной, будут выдавать ошибку с кодом 404.

Ошибка 404 - такой страницы нет

Ошибка 404 — такой страницы нет

Решение простое. Нужно настроить Nginx так, чтобы все запросы к страницам обрабатывались через index.php. Найдите файл конфигурации сайта (скорее всего, это будет nginx.conf или какой-то другой *.conf в каталоге /etc/nginx) и поищите такой блок:

location / {
try_files $uri $uri/ =404;
}

Замените его на:

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

Строки «try_files $uri $uri/ =404;» и/или блока «location / { }»  может не быть (отсутствие второго маловероятно, без него сайт вообще не должен работать), тогда просто добавьте правильный вариант.

После перезапустите службу nginx, чтобы настройки вступили в силу, затем зайдите в админку сайта — Настройки — Постоянные ссылки и нажмите «Сохранить». Готово, страницы должны открываться корректно!

Совет: когда нужно быстро запустить сайт на WordPress с работающим ЧПУ, я использую такой шаблон:

server {
listen ip_сервера:80;
server_name доменное_имя_сайта;
root "путь_до_корневого_каталога_сайта";
index index.php;
location ~ .php$ {
try_files $uri =404;
}
location / {
try_files $uri $uri/ /index.php?q=$uri$args;
}
}

Для работы на «постоянке» не рекомендую, так как не указано хранение логов и нет никаких настроек безопасности, но если намудрили с настройкой Nginx, можете начать с него.

Although this issue has been answered many times but still its not working for me.
I am getting 404 on all pages except home page on Nginx.

I am posting in my configuration below:

server {
        listen 80 ;
        listen [::]:80;

        root /var/www/html/p/swear;
        index index.php index.html index.htm;

        server_name skinnybikiniswimwear.org;

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


            location ~ .php$ {
                fastcgi_split_path_info ^(.+.php)(/.+)$;
                try_files $uri /index.php?args =404;
                fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }
}

I am not able to find the issue in this configuration.

WordPress is installed at: /var/www/html/p/swear

Thanks

asked Aug 5, 2017 at 13:17

viv's user avatar

Try this :

    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_files $uri $uri/ /index.php?$is_args$args =404;
    }


    if (!-e $request_filename) {
            rewrite ^.*$ /index.php last;
    }

Having had a lot of failures configuring wordpress to work with nginx, the rewrite rule solves every issue with the 404 errors.

answered Aug 5, 2017 at 14:22

Kris's user avatar

KrisKris

4281 gold badge4 silver badges15 bronze badges

0

try removing slash in front of /$uri/

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

location ~ .php$ {
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_pass php;
}

answered Aug 5, 2017 at 13:23

ewwink's user avatar

ewwinkewwink

18.2k2 gold badges44 silver badges54 bronze badges

9

Images does not because you dont have nothing in your server block about images. You have to add the images into your server block.

For example:

location ~* ^.+.(jpe?g|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mp3)$ {
        root /home/example/public_html
    }

answered Aug 5, 2017 at 15:59

Noob's user avatar

NoobNoob

7328 silver badges29 bronze badges

3

Как настроить Nginx так, чтобы посты и страницы при включённых ЧПУ открывались корректно.

В WordPress можно использовать человеко-понятные url (ЧПУ), чтобы из адреса страниц и людям, и поисковым системам сразу становилось понятно, о чём содержимое. Например, взглянув на tx8.ru/kak-podruzhit-tt-rss-i-fail2ban/, видно, что на странице информация про настройку fail2ban. ЧПУ включаются в админке сайта, раздел «Настройки постоянных ссылок».

Настройки постоянных ссылок в WordPress

Настройки постоянных ссылок в WordPress

Так вот, любой режим именования ссылок, кроме простого (простой — это не ЧПУ), в стандартной конфигурации веб-сервера Nginx не работает. Все страницы, кроме главной, будут выдавать ошибку с кодом 404.

Ошибка 404 - такой страницы нет

Ошибка 404 — такой страницы нет

Решение простое. Нужно настроить Nginx так, чтобы все запросы к страницам обрабатывались через index.php. Найдите файл конфигурации сайта (скорее всего, это будет nginx.conf или какой-то другой *.conf в каталоге /etc/nginx) и поищите такой блок:

location / {
try_files $uri $uri/ =404;
}

Замените его на:

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

Строки «try_files $uri $uri/ =404;» и/или блока «location / { }»  может не быть (отсутствие второго маловероятно, без него сайт вообще не должен работать), тогда просто добавьте правильный вариант.

После перезапустите службу nginx, чтобы настройки вступили в силу, затем зайдите в админку сайта — Настройки — Постоянные ссылки и нажмите «Сохранить». Готово, страницы должны открываться корректно!

Совет: когда нужно быстро запустить сайт на WordPress с работающим ЧПУ, я использую такой шаблон:

server {
listen ip_сервера:80;
server_name доменное_имя_сайта;
root "путь_до_корневого_каталога_сайта";
index index.php;
location ~ .php$ {
try_files $uri =404;
}
location / {
try_files $uri $uri/ /index.php?q=$uri$args;
}
}

Для работы на «постоянке» не рекомендую, так как не указано хранение логов и нет никаких настроек безопасности, но если намудрили с настройкой Nginx, можете начать с него.

Nginx make sites faster. It definitely has an upper edge in serving static content. That’s why, many WordPress users switch to Nginx.

Often, this switch cause Nginx WordPress permalinks 404 errors. This happens as Apache’s rewrite rules do not work with NGINX.

Therefore, fixing WordPress websites is one of the common task that we do as part of our Server Administration Services.

Today, we’ll see how Bobcares’ Engineers fixed Nginx WordPress permalinks 404 error for one of our customer.

Details of WordPress permalinks 404 error

We’ll begin with seeing the details of the error reported by the customer. The Help-desk request said:

In my domain, only the home page is working, where as every other page returns a 404 not found error. I
think this is either due to .htaccess file, permalink settings, or Nginx Configuration? Please fix!

The customer had website hosted on a Plesk server. He recently switched to Nginx from Apache. That’s when he started getting 404 or Page not found errors.

What causes permalinks 404 error in Nginx?

WordPress come with the option to create permanent links to blog posts on the website.  And, the links can be created based on post name, post number, date, etc.

Now, its time to see what causes the Nginx wordpress permalinks 404 error.

Basically, customer choose PHP-FPM as the PHP handler, as it is the handler that WordPress recommends. And, to take advantage of NGINX, we recommend customers to enable PHP-FPM on all domains that serve PHP content.

Unfortunately, mod_security rules will not work with NGINX, and .htaccess rewrite rules and restrictions will no longer apply. Nginx and Apache rewrite rules have totally different format. The directives in Apache like Rewritecond, RewriteRule, etc. take its equivalents in Nginx configuration.

This means that WordPress permalink rewrites will no longer work after switching the web server.

Steps for fixing Nginx wordpress permalinks 404 error

Luckily, there are several methods to fix the WordPress permalinks on Nginx. Let’s take a look at each of them.

1. Converting rewrite rules to Nginx format

A quicker method to fix the permalink error is to convert the Apache rewrite rules to Nginx format. Either we can manually rewrite the rules or use various plugins for automatic conversion.

For example, in servers with Plesk control panel, there comes an extension like “htaccess to nginx“. By using this extension, it would rewrite the custom Apache directives according to the rules of nginx syntax. The plugin details are as shown below.

We just had to add the rules in the Additional Nginx directives section inside the domain settings as shown below.

That fixed the permalinks and the website started working again.

2. Modifying Nginx configuration

Similarly, modifying the Nginx configuration also helps in solving the WordPress permalinks 404 error. Here, within the per domain Nginx configuration file for the domain, our Support Engineers edit the following location block within the server block:

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

Further, we reload the Nginx configuration for the changes to take effect.

3. Tweaking Proxy mode

Similarly in Plesk servers having Apache with Nginx as reverse proxy, tweaking domain’s setting also solve the permalink errors. The .htaccess is ignored if Apache is turned off for the domain. And, it results in Permalink 404 errors.

Therefore, in some cases, to solve the error, we turn ON the option Proxy mode from Plesk > Domains > example.com > Apache & nginx Settings.

[Finding Nginx WordPress permalinks 404 error trouble? We can fix your website.]

Conclusion

To be precise, Nginx wordpress permalinks 404 error occurs when the rewrite rules do not follow the Nginx format. The fix involves converting the rules, modifying Nginx configuration and many more. Today, we saw how our Support Engineers solved the error for our customer and made permalinks working again.

PREVENT YOUR SERVER FROM CRASHING!

Never again lose customers to poor server speed! Let us help you.

Our server experts will monitor & maintain your server 24/7 so that it remains lightning fast and secure.

GET STARTED

var google_conversion_label = «owonCMyG5nEQ0aD71QM»;

Tested with

  • Nginx 1.19.0
  • WordPress 5.4
  • PHP 7.2.24
  • Vesta CP

After switched to Nginx from Apache server WordPress started showing 404 or Page not found errors. Homepage loads but all permalinks are 404 when using Nginx & PHP-FPM

What causes the Nginx wordpress permalinks 404 error

WordPress recommends PHP-FPM as the PHP handler to take advantage of NGINX. Unfortunately, mod_security rules will not work with NGINX, and .htaccess rewrite rules and restrictions will no longer apply. Nginx and Apache rewrite rules have a totally different format. This means that WordPress permalink rewrites will no longer work after switching the webserver.

Similarly, modifying the Nginx configuration also helps in solving the WordPress permalinks 404 error. Here, within the per domain Nginx configuration file for the domain. Edit both nginx.conf and nginx.ssl.conf files to make it work on http:// and https://

  • /home/admin/conf/web/domain-name.nginx.conf
  • /home/admin/conf/web/domain-name.nginx.ssl.conf

edit the following location block within the server block:

cd /home/admin/conf/web/
vim domain-name.nginx.ssl.conf
// vim domain-name.nginx.conf
// press i to enter vim insert mode
//add try_files $uri $uri/ /index.php?$args; under location / {} block
location / {
    # file ($uri) or directory ($uri/)? if not, redirect to /index.php + query string
    try_files $uri $uri/ /index.php?$args;
    index  index.html index.htm index.php;
}
// press ESC to exit from vim insert mode
:wq // save and quit configuration file

For more Vim editor command read this post Basic Vim Commands to start work with Vim Editor

Here is another solution, you can try this if the previous one is not working for you. I have tested both on my Linode server and both worked perfectly.

location / {
    rewrite ^/(.*)$ /index.php?$1;
    index  index.html index.htm index.php;
}

Further, we reload the Nginx configuration for the changes to take effect.

Although this issue has been answered many times but still its not working for me.
I am getting 404 on all pages except home page on Nginx.

I am posting in my configuration below:

server {
        listen 80 ;
        listen [::]:80;

        root /var/www/html/p/swear;
        index index.php index.html index.htm;

        server_name skinnybikiniswimwear.org;

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


            location ~ .php$ {
                fastcgi_split_path_info ^(.+.php)(/.+)$;
                try_files $uri /index.php?args =404;
                fastcgi_pass unix:/var/run/php/php7.1-fpm.sock;
                fastcgi_index index.php;
                include fastcgi_params;
        }
}

I am not able to find the issue in this configuration.

WordPress is installed at: /var/www/html/p/swear

Thanks

asked Aug 5, 2017 at 13:17

viv's user avatar

Try this :

    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_files $uri $uri/ /index.php?$is_args$args =404;
    }


    if (!-e $request_filename) {
            rewrite ^.*$ /index.php last;
    }

Having had a lot of failures configuring wordpress to work with nginx, the rewrite rule solves every issue with the 404 errors.

answered Aug 5, 2017 at 14:22

Kris's user avatar

KrisKris

4281 gold badge4 silver badges15 bronze badges

0

try removing slash in front of /$uri/

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

location ~ .php$ {
    try_files $uri =404;
    include fastcgi_params;
    fastcgi_pass php;
}

answered Aug 5, 2017 at 13:23

ewwink's user avatar

ewwinkewwink

17.9k2 gold badges43 silver badges54 bronze badges

9

Images does not because you dont have nothing in your server block about images. You have to add the images into your server block.

For example:

location ~* ^.+.(jpe?g|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mp3)$ {
        root /home/example/public_html
    }

answered Aug 5, 2017 at 15:59

Noob's user avatar

NoobNoob

7228 silver badges29 bronze badges

3

Есть довольно много плагинов WordPress, которые помогут вам управлять ошибкой 404, чтобы улучшить ваш SEO. Ошибка 404 не найдено может возникнуть из-за удаления старых постов или страниц и не создает редирект или от спам-ботов. Это руководство покажет вам, как использовать Nginx для перенаправления ошибок 404 на главную страницу WordPress.

Это руководство требует Nginx и корневого доступа, так что вы можете изменить ваши виртуальные хосты Nginx.

Откройте виртуальный хост Nginx

sudo nano /etc/nginx/sites-available/andreyex.ru

Добавьте этот фрагмент в блоке сервера

# определить страницу ошибки
error_page 404 = @notfound;

# Адрес страницы ошибки 301 для редиректа
location @notfound {
    return 301 /;
}

Если вы не хотите делать 301 постоянную переадресацию, вы можете в место этого использовать 302 (временный редирект)

# определить страницу ошибки
error_page 404 = @notfound;

# адрес страницы ошибки 302 для перенаправления
location @notfound {
    return 302 /;
}

В РНР блоке установить fastcgi_intercept_errors в on

В качестве альтернативы вы можете поместить его в файл nginx.conf в блок http { block

location ~ .php$ {
    include /etc/nginx/fastcgi_params;
    # перехват ошибки 404 для редиректа
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/run/php/php7.0-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

Для наглядности здесь приведен пример виртуального хоста в Nginx для WordPress с указанными выше добавками

server {
    listen 80;
    server_name andreyex.ru;

    root /var/www/nginx/andreyex.ru;
    index index.php index.html;

    access_log /var/log/nginx/andreyex.ru.log;
    error_log /var/log/nginx/andreyex.ru.error.log;

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

    # определить страницу ошибки
    error_page 404 = @notfound;

    # расположение страницы ошибки для редиректа 301
    location @notfound {
        return 301 /;
    }

    location ~ .php$ {
        include /etc/nginx/fastcgi_params;
        # перехват ошибки 404 для редиректа
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/run/php/php7.0-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    location ~ /.ht {
        deny all;
    }

    location = /nginx.conf {
        deny all;
    }
}

Проверьте ваш синтаксис виртуального хоста Nginx перед активацией

sudo nginx -t

Если ваш синтаксис был ОК, то перезагрузить службу Nginx

sudo service nginx reload

Это должно работать!

Nginx. Перенаправление ошибки 404 на главную страницу в WordPress

Если вы нашли ошибку, пожалуйста, выделите фрагмент текста и нажмите Ctrl+Enter.

Since we all know, 404 errors directly affect our website’s SEO, since this is concerned with SEO. I am going to share with you a tip through which you can enhance your website’s SEO performance by allowing 404 errors pages to redirect to the Home page in WordPress.

I will be sharing with you step by step tutorial to work with nginx server to redirect 404 (not found) web page to WordPress homepage.

Before we begin, a user must have root access using SSH credentials. It allows user to update nginx virtual host.

NGINX Redirecting 404 Error to WordPress Homepage

Hit the below command to open nginx virtual host.

sudo nano /etc/nginx/sites-available/positronx.io

Include the given below code in the nginx server block file.

# added error page
error_page 404 = @notfound;
# 301 permanent redirection
location @notfound {
    return 301 /;
}

We used 301 redirections in the above code example just like that we can also implement 302 temporary redirection using NGINX virtual server host.

# added error page
error_page 404 = @notfound;
# 301 temporary redirection
location @notfound {
    return 302 /;
}

There are 2 ways through which you can set fastcgi_intercept_errors to on state.

1 – You can go to php block and set fastcgi_intercept_errors to on like given below.

fastcgi_intercept_errors on;

2 – You can go to /etc/nginx/nginx.conf file and include within the http { } code block.

# /etc/nginx/nginx.conf
location ~ .php$ {
    include /etc/nginx/fastcgi_params;
    # errors for 404 redirect
    fastcgi_intercept_errors on;
    fastcgi_pass unix:/run/php/php7.2-fpm.sock;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
server {
    listen 80;
    server_name positronx.io www.positronx.io;
    root /var/www/nginx/positronx.io;
    index index.php index.html;
    access_log /var/log/nginx/positronx.io.log;
    error_log /var/log/nginx/positronx.io.error.log;
    location / {
        try_files $uri $uri/ /index.php?$args /;
    }
    # added error page
    error_page 404 = @notfound;
    # 301 permanent redirection
    location @notfound {
       return 301 /;
    }
    location ~ .php$ {
        include /etc/nginx/fastcgi_params;
        # errors for 404 redirect
        fastcgi_intercept_errors on;
        fastcgi_pass unix:/run/php/php7.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
    location ~ /.ht {
        deny all;
    }
    location = /nginx.conf {
        deny all;
    }
}

Use the below command to find out if your changes get some errors in nginx virtual host.

sudo nginx -t

If you get this message in your terminal this means you are ready to reload the nginx server.

# nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
# nginx: configuration file /etc/nginx/nginx.conf test is successful

Enter the below command to reload the nginx server

sudo service nginx reload

Nginx make sites faster. But, Nginx causes WordPress permalinks 404 errors. This happens as Apache’s rewrite rules do not work with NGINX.  On this post we will learn to WordPress permalinks in Nginx.

WordPress pretty permalinks optimized to be SEO friendly and are compatible with the most popular web servers:

  • Apache: using mod_rewrite module.
  • Nginx: using try-files.
  • Lighttpd: using mod_rewrite or a 404 handler.
  • Microsoft IIS 7+ using URL Rewrite 1.1+ module and PHP 5 running as FastCGI
  • Microsoft IIS 6+ working with ASAPI_Rewrite or Ionic ISAPI Rewriting Filter (IIRF)

Why Nginx WordPress permalinks 404 error Page not found?

Technically, anyone who choose PHP-FPM as the PHP handler, as WordPress recommends. And, to take advantage of NGINX, i recommend to enable PHP-FPM on all domains that serve PHP.

Unfortunately, mod_security rules will not work with Nginx, and .htaccess rewrite rules and restrictions will no longer apply. Nginx and Apache rewrite rules have totally different format. The directives in Apache like Rewritecond, RewriteRule and more take its tolls in Nginx configuration. This means that WordPress permalink rewrites will no longer work after switching to Nginx.

Fixing Nginx WordPress permalinks 404 error Page not found

We can set our really cool permalink configuration directly by editing Nginx. We will use try_files directive so WordPress can start using pretty permalinks. Let’s see the configuration for WordPress installed on the root of your domain.

Search for the location / block inside nginx configuration and add the following line inside:

location / {
	 # WordPress permalinks in Nginx
	 try_files $uri $uri/ /index.php?$args;
}

On this code, we are letting Nginx checking the existance of a file at the URL usign $uri, then it searches for directory ($uri/), and if it doesn’t find any of both, it will make an internal redirect to /index.php with the arguments from the query string as parameters.

After editing, save your file, and reload Nginx to apply changes:

service nginx reload

or

systemctl reload nginx.service

Alternatively, in servers with Plesk control panel, we just had to add the rules in the “Additional Nginx directives” section inside the domain settings at Domains > example.com > Apache & nginx Settings. That fixed the permalinks and the website started working again.

if (!-e $request_filename) {
set $test P;
}
if ($uri !~ ^/(plesk-stat|webstat|webstat-ssl|ftpstat|anon_ftpstat|awstats-icon|internal-nginx-static-location)) {
set $test "${test}C";
}
if ($test = PC) {
rewrite ^/(.*)$ /index.php?$1;
}

On the other hand, in servers with CPanel. Please bear in mind that Nginx configuration file refers to the user’s config file at this location where $USERNAME represents the username:

/etc/nginx/conf.d/users/$USERNAME.conf

Next, you need to add this snipprt to the config file above: (/wordpress here refers where the WordPress installation is configured to be available)

location /wordpress { try_files $uri $uri/ /wordpress/index.php?$args; location ~ .php7?$ { include conf.d/includes-optional/cpanel-fastcgi.conf; fastcgi_pass unix:/opt/cpanel/ea-php73/root/usr/var/run/php-fpm/1ed179754201ac2644e8c70140bacb23c7786484.sock; error_page 502 503 /FPM_50x.html; } }

Finally, you restart Nginx gracefully by running this command:

/scripts/restartsrv_nginx

Conclusion

Nginx wordpress permalinks 404 error page not found occurs when the rewrite rules do not follow the Nginx format. The fix involves converting the rules and modifying Nginx configuration.

Понравилась статья? Поделить с друзьями:
  • Wordpress ошибка 403 доступ запрещен как исправить
  • Wordpress ошибка 401
  • Wordpress отключить вывод ошибок
  • Wordpress журнал ошибок
  • Wordpress главная страница 404 ошибка