Ошибка 404 кроме главной страницы

Если главная страница сайта отображается, а внутренние выдают ошибку 404 или 500, проблема заключается в отсутствии файла .htaccess или его неправильном содержании.

Внутренние страницы перестают открываться на CMS (WordPress, Joomla, DLE), поскольку в этих системах файл .htaccess имеет большое значение и часто видоизменяется. Проблема появляется при переносе сайта с одного виртуального хостинга на другой.

Оглавление статьи:

  • Причины и решение ошибки 404/500
  • Файл .htaccess для WordPress
  • Хостинг на Windows и панель ISPmanager

Причины и решение ошибки 404/500

Файл .htaccess должен содержать записи, необходимые для работы CMS. При переносе сайта на новый хостинг, особенно через браузерные версии панелей хостеров, данный файл может не попасть в архив из-за настроек безопасности. Как следствие, на новом хостинге файла не будет, и правильно развернутая из бекапа и настроенная CMS работать не будет — кроме главной страницы. Наиболее часто проблема наблюдается на сайтах, где вместо стандартного отображения URL подключено ЧПУ.

Внутренние страницы перестают открываться, если:

  1. Файл .htaccess отсутствует. Проблема актуальна при переносе сайта с одного хостинга на другой.
  2. Файл пустой. Содержимое файла может быть удалено по ошибке, в результате заражения сайта вирусами или по иной причине.
  3. Содержимое файла изменено или повреждено. Если внутренние страницы сайта перестали работать после каких-либо действий с .htaccess, следует проверить файл на наличие всех директив, необходимых для работы CMS.

Страница 404 WordPress

Отличительной особенностью ошибки с файлом .htaccess является измененный дизайн страницы 404/500. Страницы ошибки 404 будут отдаваться сервером и отличаться от оформления 404 у сайта (с шаблоном и дизайном, элементами навигации). Актуально, по крайней мере, для WordPress.

Для исправления ошибок нужно создать .htaccess с нужным содержимым. Содержание файла будет меняться в зависимости от CMS. Помимо указанного кода, в файле может содержаться любая информация и директивы, необходимые для функционирования сайта.

Файл .htaccess для WordPress

Каждая система управления контентом требует определенных директив для полноценного и корректного функционирования. Документ .htaccess должен располагаться в корне сайта и иметь, как минимум, указанное ниже содержание (для WordPress).

# BEGIN WordPress

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]

# END WordPress

Содержимое файлов для других популярных CMS можно без проблем найти в сети — там текста в разы больше, и в статью информация попросту бы не влезла. У WordPress содержимое файла не менялось годами, а потому ошибка одинаково хорошо решается на всех версиях движка.

Хостинг на Windows и панель ISPmanager

Любые операции с файлом .htaccess актуальны только для хостингов, расположенных на Linux-серверах. Сервера от Windows попросту не имеют такого файла — вместо него аналогичные функции выполняются в документе web.config. Уточнять содержимое данного файла следует в поддержке соответствующей CMS.

Помимо этого, проблема с ошибкой 404 на внутренних страницах актуальна для Linux-серверов с панелями ISPmanager. В этом случае требуется отключить автоподдомены, если они включены, и проверить наличие проблемы. Ошибки 404 и 500 могут исчезнуть и без замены .htaccess (либо с файлом изначально все нормально, если он присутствует в корне и правильно заполнен).

All of a sudden I go to my WordPress website and all the pages give me a 404 page not found page. I’m assuming the problem lies with the permalink structure, which I could swear I did not touch. The permalink setting is on «month and name.»

I’ve researched similar instances of this problem online and a lot of it has to do with the .htaccess file? I tried finding, but I can’t. Perhaps it got deleted somehow? Where is it supposed to be located.

Any suggestions will be helpful

and of course I can see hidden files.

Marc's user avatar

Marc

4,5013 gold badges41 silver badges62 bronze badges

asked Mar 3, 2011 at 15:07

Adam's user avatar

2

.htaccess is a hidden file, so you must set all files as visible in your ftp.

I suggest you return your permalink structure to default ( ?p=ID ) so you ensure that .htaccess is the problem.

After that, you could simply set «month and name» structure again, and see if it works.

PS: Have you upgraded to 3.1? I’ve seen some people with plugin issues in this case.

answered Mar 3, 2011 at 15:18

Rochester Oliveira's user avatar

9

Basically the .htaccess file should exists and the httpd.conf should be correct.

In my case, I changed the file /etc/apache2/apache2.conf in section:

<Directory "/var/www/html">

Line changed is:

AllowOverride None

to

AllowOverride All

And restart the web server with

systemctl restart apache2

Community's user avatar

answered Sep 9, 2016 at 4:52

georgeos's user avatar

georgeosgeorgeos

2,2382 gold badges24 silver badges27 bronze badges

5

Fixing that problem is very simple if you was using permalinks other than the default such as Day and name, Month and name, Numeric, Post name or Custom Structure, you only need to

Login to your admin area: Settings > Permalinks which should be : http://yoursite.com/wp-admin/options-permalink.php

Choose Default permalink setting, then save changes

Then you can return it again to your other previous permalink choice or keep it as default as yo wish

Note that this problem can happen when you move your site from a domain or location to another one.

answered Sep 27, 2013 at 19:59

usama sulaiman's user avatar

usama sulaimanusama sulaiman

1,9933 gold badges24 silver badges37 bronze badges

8

If the default behavior (example.com/?p=42) is working, you should:

  • Change to your preferred permalink style: Admin: Settings > Permalinks, and click Save. Sometime it fixes the issue. If it didn’t:
  • Verify that the file /path/to/wordpress/.htaccess has been changed and now includes the line RewriteEngine On. If it doesn’t include the line, it’s a WordPress permissions issue.
  • Verify that the ‘rewrite’ module is loaded: create a PHP file with

    <?php
      phpinfo()
    ?>
    

    in it, open it in the browser and search for mod_rewrite. It should be in the ‘Loaded Modules’ section.
    If it’s not, enable it — Look at your apache default index.html file for details — in Ubuntu, you do it with the helper a2enmod.

  • Verify that apache server is looking at the .htaccess file. open httpd.conf — or it’s Ubuntu’s alternative, /etc/apache2/apache2.conf. In it, You should have something like

    <Directory /path/to/wordpress>
      Options Indexes FollowSymLinks
      AllowOverride All
      Require all granted
    </Directory>
    
  • After making these changes, don’t forget to restart your apache server. sudo service apache2 restart

RyanS's user avatar

RyanS

6271 gold badge10 silver badges26 bronze badges

answered Jan 30, 2017 at 2:06

tsvikas's user avatar

tsvikastsvikas

15.3k1 gold badge19 silver badges11 bronze badges

0

IF all this dont work, your .htaccess is correct, and permalinks trick didnt work, you may have not enabled your apache2 rewite mod.

I ran this and my issue was solved:

 sudo a2enmod rewrite 

answered Feb 20, 2018 at 18:06

David Valenza's user avatar

2

Within the WordPress admin interface do the following:

  1. Go to admin setting

  2. Click on permalink and select post name in radio button.

  3. Scroll down and you will see .htaccess code here like.

    <IfModule mod_rewrite.c>
        RewriteRule ^index.php$ - [L]
        RewriteCond %{REQUEST_FILENAME} !-f
        RewriteCond %{REQUEST_FILENAME} !-d
        RewriteRule . /wordpress/index.php [L]
    </IfModule> 
    
  4. Copy the code and paste in the .htaccess file.

Blackbam's user avatar

Blackbam

16.3k24 gold badges94 silver badges146 bronze badges

answered Mar 14, 2014 at 10:24

Mahesh singh chouhan's user avatar

3

This error is causing due to disabled of rewrite mod in apache httpd.conf document ,just uncomment it and enjoy the seo friendly permalinks

answered Apr 5, 2013 at 22:34

Asif Khan's user avatar

Asif KhanAsif Khan

811 silver badge1 bronze badge

  • Check that the directory on .htaccess are the correct
  • Check the fields «siteurl» and «home» are the correct

answered Mar 4, 2011 at 7:07

José Carlos's user avatar

José CarlosJosé Carlos

1,00516 silver badges29 bronze badges

1

We had the same problem and solved it by checking the error.log of our virtual host. We found the following message:

AH00670: Options FollowSymLinks and SymLinksIfOwnerMatch are both off,
so the RewriteRule directive is also forbidden due to its similar
ability to circumvent directory restrictions :
/srv/www/htdocs/wp-intranet/

The solution was to set Options All and AllowOverride All in our virtual host config.

answered Jul 3, 2018 at 14:48

Black's user avatar

BlackBlack

17k36 gold badges150 silver badges256 bronze badges

If you have FTP access to your account:

First, login to your wp-admin and go to Settings > Permalinks

You should see something at the bottom that says:

«If your .htaccess file were writable, we could do this automatically, but it isn’t so these are the mod_rewrite rules you should have in your .htaccess file. Click in the field and press CTRL + a to select all.»

If this is true do the following:

  1. Go into preferences for your FTP client and make sure hidden files are displayed (varies depending on your FTP client) — If you don’t do this you won’t be able to find your htaccess file

  2. Go to the folder that your wp-admin, wp-content, wp-includes directories are located. Check for .htaccess file. If it exists skip to step 4

  3. If it does not exist, create a new blank file in your FTP program called .htaccess

  4. Change the CHMOD for your .htaccess file to 666 (your preference on how you want to do this)

  5. Go back to your Permalinks page and edit the link structure you want. Problem should be solved!

  6. Make sure to change the chmod of the htaccess file back to 644 after you are done.

Just had the same problem and it seemed to fix it instantly! Good luck!

answered Oct 12, 2012 at 16:47

JEFF B's user avatar

JEFF BJEFF B

1262 silver badges12 bronze badges

1

Most of the time this issue is fixed by simply visiting the Settings -> Permalink page in the WordPress admin and click Save (as several other answers already pointed out). When this page is accessed, WordPress rewrites the directives in the .htaccess file which magically fixes the issue. The issue often happens after moving a site (the site breaks because the .htaccess gets left behind or the settings need to be updated).

If WordPress doesn’t have the right permissions to write the .htaccess file, a notice will appear at the top of the page and further instructions at the bottom when the settings are saved. In this case you need to edit the .htaccess file yourself or, better, to fix the permissions on that file. The file is at the root of the WordPress installation. cd into the directory and sudo chmod 644 .htaccess. You might also want to check if the file belongs to the right group and change that is needed with chown. Ask your hosting provider if you don’t know how to do that.

If you are on shared hosting that’s probably all you can do. If you still have the issue you might want to talk to you hosting provider’s support. Otherwise, make sure the use of .htaccess files is enabled on the server, as @georgeos already suggested. Note that httpd.conf is not always used (Ubuntu indicates it is deprecated but the official Apache docs still says it is often the main configuration file). /etc/httpd/conf/httpd.conf and /etc/apache2/apache2.conf seem to be the most common places for this file. Find the block for the public folder, usually <Directory /var/www/> and make sure that the AllowOverride directive is set to All. If it is set to None, your .htaccess file is simply ignored by the server.

answered Aug 15, 2017 at 23:45

mrtnmgs's user avatar

mrtnmgsmrtnmgs

1,32413 silver badges26 bronze badges

You may have .htaccess disallowed in webhost settings.
Setting to default permalinks would work in that case.

answered Feb 28, 2017 at 14:34

Fanky's user avatar

FankyFanky

1,5741 gold badge17 silver badges19 bronze badges

Case 1:- Let us think if migrate site from one hosting to another hosting if see this kind of issue.

Solution:- Simply go to old server copy .htaccess file code, then past in new server .htaccess file. 99% it i will works.

answered Nov 7, 2017 at 5:05

Navruk's user avatar

NavrukNavruk

9276 gold badges17 silver badges29 bronze badges

Before trying to do any permalink or server config changes, please check you .htaccess file. This mostly is a corrupt or blank .htaccess file issue. Reset the htaccess file to the default

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

answered Mar 15, 2019 at 11:37

Mustafa sabir's user avatar

Mustafa sabirMustafa sabir

4,1001 gold badge18 silver badges27 bronze badges

0

after 2 long days,
the solution was to add options +FollowSymLinks to the top of my .htaccess file.

answered Apr 4, 2020 at 2:29

Ahmad Ali's user avatar

Ahmad AliAhmad Ali

6641 gold badge13 silver badges28 bronze badges

I have the same problem and so I remove the Apache and make it again and the problem was solved.

answered Jun 6, 2013 at 16:38

boomz's user avatar

boomzboomz

6575 silver badges21 bronze badges

Just Navigate to Settings->Permalink in your dashboard and then Save Changes button in the last.

answered Jul 13, 2017 at 10:30

Deepak Sharma's user avatar

I just changed the permalink to ‘month and day’of all the posts by ging to setting>permalink.

Now all posts are open and working fine.

Again, I renamed to all posts to its actual permalink. Its again working fine.

This method worked for me :-)

answered May 20, 2018 at 13:57

Shani Deshwal's user avatar

For nginx users

Use the following in your conf file for your site (usually /etc/nginx/sites-available/example.com)

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

This hands off all permalink requests to index.php with a URI string and supplied arguments. Do a systemctl reload nginx to see the changes and your non-homepage links should load.

answered Jun 14, 2018 at 14:24

ABC Taylor's user avatar

Go to your WordPress Dashboard, scroll down to settings, select Permalink,

in custom settings that appear, go to custom structure and replace the text in the text field with

/index.php/%year%/%monthnum%/%day%/%postname%/

and then save changes

answered Jul 7, 2021 at 14:42

Insookwa's user avatar

InsookwaInsookwa

791 silver badge5 bronze badges

Wanted to share my two cents. Recently came accross that very same issue installing WordPress 5.9. Year 2021.

Configuration:

Platform MAC, Software XAMPP, WordPress 5.9

None of the previous answer did it for me.

The issue was due to the fact that files permissions accross the XAMPP folder were set to «Read only».

  1. Locate the XAMPP folder. (Usually in the Applications folder).
  2. Right click XAMPP folder.
  3. Get info.
  4. Bottom right unlock button → Follow instructions.
  5. Sharing and permissionsEveryoneRead & Write.
  6. Bottom left three dots button → Apply to enclosed items.

answered Jan 29, 2022 at 10:39

amarinediary's user avatar

amarinediaryamarinediary

4,5504 gold badges25 silver badges40 bronze badges

This scenario can also be caused by a database version that’s out of sync with the WP files installed on server. Nothing else listed here worked for me; I solved it with a manual WP update.

answered Nov 1, 2022 at 20:40

Blorf's user avatar

BlorfBlorf

5163 silver badges12 bronze badges

I had this issue not so long ago. I had reset my permalink to default or just saved it, updated themes/core to (4.7.4)/plugins, deactivated all plugins, switched to default theme, optimized database, .htaccess is already default, checked file permissions, mod_rewrite is on.

So far nothing works, what works are the posts, new page, the /contact page EXCEPT for old pages.

Basically, the pages/URLs that aren’t working are:

/breeding
/training
/training/*
/breeding/*

Ultimate, I found these files in the root folder:

/breeding.php and /training.php

I renamed both files and the pages above worked.

answered May 16, 2017 at 16:05

Loreto Gabawa Jr.'s user avatar

It is common that you come across the WordPress 404 or “WordPress site permalinks not working” error on your website if it is not appropriately maintained. But there are times when your website is under maintenance, and your visitors will be automatically directed to a 404 error page.

Are you facing a WordPress 404 error or a “WordPress page not found” error? Don’t freak out! We have a solution for you.

  • What is a WordPress 404 Error?
  • How to Fix 404 Error on WordPress (8 Solutions)
    1. Clear the Browsing Cache and Cookies
    2. Set Your Permalinks
    3. Restore Your .htaccess file
    4. Set Up a 301 Redirect
    5. Disabling Plugins/Themes
    6. Change and Update WordPress URL in Database
    7. Fix WordPress 404 Error on Local Servers
    8. Alternative Method
  • Conclusion

What is a WordPress 404 Error?

The 404 error is an HTTP response code that occurs when the server cannot find the file or page requested by the user. In response, the web hosting server automatically sends the user an error message, “404 Not Found“.

The WordPress 404 error commonly occurs when:

  • You’ve newly migrated your site to a new host.
  • You have changed your URL’s permalink structure and haven’t redirected the old URL.
  • You don’t have file permissions.
  • You have opened an incorrect URL.
  • Poorly coded plugin/theme.

Many WordPress themes offer creative layouts & content options to display the 404 error page. Cloudways’ 404 error has a custom design and layout too:

404 error

Managed WordPress Hosting Starting from $10/month.

Enjoy hassle-free hosting on a cloud platform with guaranteed performance boosts.

How to Fix 404 Error on WordPress (8 Troubleshooting Solutions)

This tutorial will show you how to quickly fix the 404 Not Found status code. So let’s get started!

1. Clear Browser History & Cookies

The first troubleshooting method you should try is clearing the browser cache and cookies. Or you can try to visit your site in incognito mode.

2. Set Up Your Permalink

If apart from your homepage, your other WordPress website pages give you a 404 page not found error, you can update your permalink settings by following the steps below:

  • Log in to your WordPress Dashboard.
  • Go to SettingsPermalinks.
  • Select the Default settings.
  • Click the Save Changes button.
  • Change the settings to the previous configuration (the one you selected before Default). Put the custom structure back if you had one.
  • Click Save Settings.

Note: If you use a custom structure, copy/paste it into the Custom Base section.

custom structure setting

This solution could fix the WordPress 404 not found or “WordPress permalinks not working” error.

If it doesn’t work, you’ll need to edit the .htaccess file in the main directory of your WordPress installation (where the main index.php file resides). 404 errors are also usually due to misconfigured .htaccess files or file permission-related issues.

3. Restore Your .httaccess File

Since .htaccess is a hidden file, you must set all files as visible in your FTP.

Note: It’s always recommended to backup your site before editing any files or pages.

Follow the steps below:

  • Log in to your server using an FTP client.
  • Download the .htaccess file which is located in the same location as folders like /wp-content/ wp-admin /wp-includes/.
  • Open the downloaded file in any text editor.
  • Visit the WordPress .htaccess support page and copy/paste the version of the code that is most suitable for your website.
  • Save the .htaccess file and upload it to the live server.

public folder

For example, if you have Basic WP, use the code below.

# BEGIN WordPress

RewriteEngine On

RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

RewriteBase /

RewriteRule ^index.php$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /index.php [L]

# END WordPress

4. Setup a 301 Redirect

If you have changed the URL of any specific page and haven’t redirected it yet, it’s time to redirect the old URL to your new URL. You may redirect your old post/page via a plugin or a .htaccess file.

If you are comfortable working with .htaccess, add the following code to your .htaccess file. Don’t forget to replace the URLs with your own website.

Redirect 301 /oldpage.html https://www.mywebsite.com/newpage.html

If you prefer the easy way, you may use a plugin to set up a 301 redirect. Follow the steps below:

  • Install the Redirection Plugin.
  • Go to the WordPress Dashboard.
  • Click Tools > Redirection.
  • Complete the setup and Add new redirection.

Redirection via plugin

5. Disabling Plugins/Theme

An outdated or poorly coded plugin may be causing the 404 error on your WordPress site. To check this, you must deactivate all your plugins and change your current theme.

Note: All WordPress themes have 404.php files but don’t necessarily have a custom 404 error template file. WordPress automatically uses the 404.php page if the 404 error occurs. 

You may access your WordPress files using an FTP like FileZilla. Go to public_html > wp-content and change the plugins folder name to something like myplugins.

Disabling Plugins

Now go back to your browser to check whether the website is working. If the error has been resolved, then any of your plugins could be the culprit.

Note: If it’s not resolved, simply change the myplugins folder name to plugins and move to the next troubleshooting method.

If it’s resolved, change the myplugins folder name to plugins and follow the steps below to check which of your plugin(s) is causing the error.

  • Go to your WordPress dashboard.
  • Go to Plugins > Installed Plugins.
  • Activate each plugin one by one and check if your website is working.
  • When you encounter the 404 error, you’d know which plugin caused it.
  • Update the plugin or remove it to get rid of the error.

WordPress plugins

6. Change and Update WordPress URL in Database

You might encounter the following error message on your WordPress website.

“The requested URL was not found on this server. If you entered the URL manually, please check your spelling and try again.”

Update WordPress URL

Fix the error by following the steps below:

  • Go to your PHPMyAdmin.
  • Navigate to your database name, and select wp-option. For example, blog > wp-option.

PHPMyAdmin

  • Change the URL, for example, from https://www.abc.com/blog/ to http://localhost/blog.

change the URL

7. Fix WordPress 404 Error on Local Servers

Many designers and developers install WordPress on their desktops and laptops using a local server for staging purposes. A common problem with local server installations of WordPress is the inability to get permalink rewrite rules to work.

You may try to change the permalinks for posts and pages, but eventually, the website shows the WordPress “404 Not Found” error.

Fixing Errors is Easier With Cloudways

Get rid of WordPress errors with a cloud hosting built to deliver a hassle-free experience with incredible speeds.

Start Free!

In this situation, turn on the rewrite module in your WAMP, XAMPP, or MAMP installation. I am using WAMP in this tutorial. Navigate to the taskbar and find the WAMP icon. After that, navigate to ApacheApache modules.

Fixing Errors

It will enable a long list of modules that you can toggle on and off. Find the one called “rewrite_module” and click it, so it is checked.

apache

Then check whether your permalinks are working or not.

8. Alternative Method

If none of the above solutions work, you may try the alternative method to fix the 404 error.

  • Navigate to the local server.
  • Find the Apache folder, then go to the “conf” folder.
  • Navigate to the httpd.conf file.
  • Search for a line that looks like:

#LoadModule rewrite_module modules/mod_rewrite.so

  • Remove the “#” sign so it looks like this:

LoadModule rewrite_module modules/mod_rewrite.so

Additional tip: PHP workers are used while executing your WordPress site’s code. An ecommerce site that gets 50,000 visitors per month needs a lot more resources than a simple blog with the same amount of traffic.

Conclusion

I hope this guide helped you solve the “WordPress 404 page error” or “WordPress permalinks not working” problem. Have you figured out any other ways to get rid of this problem? Please share your solutions with us in the comment section below.

Also, if you are a WordPress user and want to boost your site, you must try Cloudways WordPress hosting solutions and take advantage of its 3-day free trial.

Frequently Asked Questions

Q. Why am I getting a 404 error?

WordPress 404 errors usually occur when you have removed certain pages from your website and haven’t redirected them to your live pages. Sometimes, these errors may also occur when you have changed a URL of a specific page.

Q. How do I test a 404 error?

You can use multiple tools to test WordPress 404 errors, like Deadlinkchecker. Or you may access Google Analytics to find out which blogs are giving you a 404 error.

Q. How do I fix error 404 on WordPress?

You can fix the error 404 on WordPress by implementing the following solutions:

  • Clear the browser cache and cookies
  • Set your permalinks
  • Make a default .htaccess file
  • Set up a 301 redirect
  • Disable plugins and themes
  • Change and update the WordPress URL in the database
  • Fix the error on local servers

Q. How to redirect WordPress 404 pages?

Follow the steps below to redirect WordPress 404 pages:

  • Go to your WordPress dashboard.
  • Navigate to Tools > Redirection.
  • Apply redirection by pasting the broken URL in the source box and the new URL in the Target box.

Q. How to edit a WordPress 404 page?

You may edit a WordPress 404 page by following the steps below:

  • Visit your WordPress dashboard.
  • Navigate to Appearance > Theme Editor.
  • Find the file named “404.php file” and edit the file yourself or with the help of a WordPress developer.

Как настроить 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, можете начать с него.

Дек 10, 2020

Anna

7хв. читання

Ошибка 404: Как исправить в WordPress (3 метода)

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

В этой статье мы рассмотрим три способа исправления ошибки 404 в WordPress:

  1. Сброс настроек постоянных ссылок в WordPress (англ).
  2. Восстановление файла .htaccess (англ).
  3. Отключение тем и плагинов.

Однако, прежде чем закатывать рукава, мы поговорим о том, как работает ошибка 404 и какие причины её возникновения. Давайте перейдём непосредственно к этому!

Ошибка 404 это сообщение, которое появляется, когда вы пытаетесь получить доступ к странице, которую браузер не может найти. В зависимости от того, какой браузер вы используете, сообщение может незначительно отличаться. Например, Firefox отображает такой текст: «404 Not Found», а Chrome показывает сообщение — «404. That’s an error»:

Так выглядит ошибка 404 в Chrome

Эти сообщения об ошибках по умолчанию могут быть довольно неопределёнными, и любой веб-сайт может настроить собственную страницу ошибок 404 (англ). Это не является необходимым, но это позволяет объяснять посетителям, что сайт работает, и единственная проблема заключается в конкретной странице, которую они пытаются найти.

Независимо от того, как оно выглядит, существует много вещей, которые могут вызвать в WordPress сообщение: 404 ошибка. К ним относятся:

  • Неверный URL. В некоторых случаях ошибка может быть в дополнительной букве, набранной в URL страницы.
  • Проблемы с кэшированием. Иногда браузер может кэшировать страницу, к которой вы пытаетесь получить доступ, и пока она не найдена, вы будете видеть ошибку 404, даже если сайт работает для всех остальных.
  • Проблема с настройками сервера доменных имен (DNS). Возможно, информация о вашем домене ещё не обновилась в DNS, поэтому вы видите ошибку при попытке получить доступ к одной из страниц вашего сайта.
  • Проблемы с совместимостью в WordPress. В некоторых случаях проблемы с плагином или темой могут повлиять на то, как WordPress создаёт URL-адреса и постоянные ссылки для вашего сайта. Затем, если кто-либо попытается получить доступ к URL-адресу, который больше не работает, возникает ошибка 404 в WordPress.

Важно понимать, что ошибка 404 не уникальна только для WordPress. Она может возникать независимо от того, на какой платформе находится ваш сайт. Однако, если вы используете WordPress, у вас есть преимущество, так как существует множество способов решить эту проблему. Давайте поговорим о том, что делать, если вы столкнулись с ошибкой 404 в WordPress.

Что делать перед устранением ошибки 404 в WordPress

В следующих разделах вы будете редактировать некоторые файлы на бэкэнд WordPress. Мы проведем вас через весь процесс, и всё будет в порядке. Однако, когда вы решите редактировать конфиденциальные файлы в WordPress, лучше заранее создать резервную копию вашего сайта — на всякий случай.

Если у вас нет доступа к панели управления WordPress прямо сейчас, не волнуйтесь. В Hostinger существует несколько способов получить резервную копию вашего веб-сайта с панели управления хостингом.

Как получить резервную копию веб-сайта

После этого вам нужно будет загрузить и настроить FTP-клиент. Мы рекомендуем FileZilla (англ), так как он бесплатный и предлагает все функции, которые могут вам понадобиться. Если вы раньше не использовали FTP, вы можете ознакомиться с нашим подробным руководством о том, как получить доступ к сайту Hostinger напрямую. Затем, когда вы будете готовы, вы сможете приступить к исправлению ошибок WordPress 404.

Как исправить ошибку 404 в WordPress (3 метода)

В некоторых случаях ненайденные страницы в WordPress вскоре исчезают сами по себе. Обычно это происходит, если они вызваны ошибкой с вашим хостинг-провайдером. Прежде чем приступать к серьёзному устранению неполадок, мы рекомендуем вам попробовать обновить сайт, предоставив ему пять или десять минут, чтобы всё уладить.

Если ошибка сохраняется и дальше, значит на вашем сайте существует проблема. В этом случае давайте рассмотрим три потенциальных решения одно за другим.

1. Сбросьте настройки своих постоянных ссылок (пермалинков) в WordPress

Одной из наиболее распространённых причин ошибки WordPress 404 является проблема с тем, как WordPress генерирует ваши постоянные ссылки (англ). Как вы, возможно, знаете, WordPress предоставляет вам несколько вариантов форматирования ссылок ваших записей и страниц. Например, вы можете настроить платформу для использования простых числовых ссылок или указать название каждой записи в качестве URL-адреса:

Как переустановить постоянные ссылки

В любом случае первое, что вам нужно сделать, когда вы столкнётесь с ошибкой 404 в WordPress, это сбросить настройки ваших постоянных ссылок. Есть два способа сделать это: один через панель управления (Консоль), а другой через FTP. Если у вас есть доступ к панели управления, следуйте инструкциям в этом разделе. Еслм нет – вам следует перейти к методу номер два.

Если вы можете войти в свою панель инструментов, начните с перехода во вкладку Настройки> Постоянные ссылки. Обратите внимание на структуру, которую использует ваш сайт на данный момент. Вам нужно будет временно изменить её, чтобы сбросить настройки постоянных ссылок в WordPress, но вы измените её всего на мгновение.

Выберите параметр Простой в разделе Общие настройки и нажмите кнопку Сохранить в нижней части страницы:

Как временно изменить структуру ссылок

Страница перезагрузится. Затем вы можете продолжить и выбрать свой предыдущий тип постоянных ссылок и сохранить изменения ещё раз. Это всё, что требуется для сброса структуры ссылок на WordPress.

Теперь попробуйте просмотреть свой веб-сайт как обычно. Проверьте страницы, которые ранее выдавали ошибку 404. Если ошибка ушла, вы молодец – вам понадобилось минимум времени, чтобы её исправить!

2. Восстановите файл .htaccess в WordPress.

Когда вы вносите изменения в структуру постоянной ссылки в WordPress, они сохраняются в файл под названием .htaccess (англ). Этот файл определяет, как WordPress будет взаимодействовать со своим сервером, а также способ создания URL-адресов для страниц.

Если у вас нет доступа к панели управления, вам нужно будет вручную отредактировать .htaccess, чтобы переустановить постоянные ссылки. Чтобы начать работу, зайдите на свой сайт через FTP и перейдите в корневую папку WordPress. Это каталог, который содержит установку WordPress и обычно находится в папке public_html или www или назван в честь вашего сайта:

Как найти корневую папку WordPress

Откройте эту папку и найдите файл .htaccess. Если вы используете FileZilla, вам нужно щёлкнуть правой кнопкой мыши по файлу .htaccess и выбрать параметр Просмотреть / Изменить. Это означает, что вы загружаете копию файла на свой компьютер и открываете его с помощью локального текстового редактора по умолчанию. Теперь вы сможете внести любые изменения, которые вам нужны.

Если вы не понимаете, для чего нужен весь код в этом файле, не беспокойтесь. Вы не должны вносить в него никаких изменений, если вы не уверены в них на 100 %. Однако, что вы можете сделать, так это использовать код WordPress .htaccess, который выглядит следующим образом:

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

Это чистый файл .htaccess без каких-либо изменений. Он удалит любые изменения, внесённые в вашу структуру постоянной ссылки. Идём дальше и создаём резервную копию содержимого старого файла .htaccess и заменяем его фрагментом кода, указанного выше.

После этого сохраните изменения в файле .htaccess с помощью текстового редактора и закройте его. FileZilla спросит, хотите ли вы заменить существующий файл .htaccess копией, которую вы только что отредактировали. Согласитесь на это действие, и всё! Вы просто переустанавливаете свои постоянные ссылки WordPress вручную, не нарушая ничего в этом процессе.

На этом этапе попробуйте снова вернуться на ваш сайт. Ошибка 404 должна исчезнуть, что уже является отличной новостью. Тем не менее, вы по-прежнему можете вернуть предыдущую структуру постоянных ссылок, если вам не нравятся числовые URL-адреса.

Помните, что вы можете изменить способ просмотра ваших постоянных ссылок, перейдя в панель управления и во вкладку Настройки> Постоянные ссылки. Выберите структуру, которую использовал ваш сайт до ошибки 404, и сохраните изменения. Тогда всё должно вернуться к нормальному функционированию.

3. Отключите темы и плагины в WordPress.

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

Есть два способа сделать это, в зависимости от того, имеете ли вы доступ к панели управления или нет. Если у вас есть доступ, перейдите во вкладку Плагины> Все плагины и выполните этот процесс для каждого из ваших плагинов:

  1. Нажмите кнопку Деактивировать под именем плагина.
  2. Проверьте свой сайт, чтобы узнать, сохраняется ли ошибка 404.
  3. Если ошибка всё ещё существует, повторно активируйте отключённый плагин.
  4. Перейдите к следующему плагину в списке и повторите процесс.

Ваша цель – отключать каждый плагин один за другим. Вы можете отключить их всех сразу, но в большинстве случаев всего один плагин вызывает проблемы. Если отключение одного из ваших плагинов устраняет проблему, у вас есть три варианта. Вы можете проверить, есть ли доступное обновление, и временно отключить плагин до тех пор, пока оно не появится, или вы не замените плагин на альтернативный.

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

Как временно изменить тему

Теперь проверьте, не исчезла ли ошибка 404. Если да, то вам снова нужно выбирать между поиском обновления или поиском новой темы. Переключение тем в WordPress может быть немного хлопотным, но в конечном итоге это необходимо, раз уж ваша текущая тема приводит к ошибкам.

Если у вас нет доступа к панели управления, вы можете отключить тему и плагины вручную через FTP. Чтобы сделать это, зайдите на свой сайт с помощью FileZilla, затем перейдите в каталог public_html / wp-content. Здесь вы найдёте несколько папок, две из которых называются plugins и themes соответственно:

Как отключить плагины или тему вручную

Сначала зайдите в каталог плагинов. Вы заметите, что для каждого плагина есть своя папка. Выберите одну из этих папок, щёлкнув по ней правой кнопкой мыши и выберите опцию Переименовать:

Как переименовать папку

Измените название папки на что-то вроде akismet.disabled, так чтобы вы смогли легко её идентифицировать. Простого изменения названия папки плагина достаточно для того, чтобы WordPress его отключил. Теперь проверьте, не исчезла ли ошибка 404. Если нет, верните этой папке прежнее название и повторите этот процесс для каждого следующего плагина в папке.

Если один из ваших плагинов стал причиной ошибки, вы знаете, как с этим справиться. Однако, если окажется, что ошибка 404 возникает не из-за них, вы можете перейти в каталог тем wp-content> themes. Найдите папку с активной темой и переименуйте её так же, как и плагины:

Как переименовать папку тем

Поскольку WordPress всегда нуждается в активной теме, отключение вашей приведет к тому, что платформа будет использовать один из готовых вариантов по умолчанию. Это может повлиять на внешний вид вашего веб-сайта, но не беспокойтесь, это временно.

Если ошибка исчезла, вам может потребоваться подобрать новую тему. Однако, если это не так, восстановите предыдущее название папки своей темы, чтобы WordPress снова её распознал.

Дополнительная информация

Ошибка 404 это не единственная проблема, которая может возникнуть с веб-сайтом в WordPress. Вот список наиболее популярных ошибок в WordPress с углублённой информацией о том, как их исправлять:

  • Как исправить ошибку 403 Forbide Error в WordPress
  • Как исправить ошибку 500 Internal Server Error в WordPress
  • Ошибка 502 Bad Gateway в WordPress – причины и как исправить
  • Как отладить и исправить ошибку 503 Service Unavailable в WordPress
  • Ошибка 504 Gateway Time-out и как её исправить в WordPress
  • Как исправить ошибку HTTP при загрузке изображений в WordPress
  • Как исправить ошибку «Извините, вы не можете получить доступ к этой странице» в WordPress

Вывод

Ошибка 404 может показаться простой, но она может нанести большой урон. Если ваши посетители не могут найти нужные им страницы, они могут начать искать в другом месте, а зачем вам это? Это означает потерянный трафик и, возможно, снижение конверсий.

К счастью, есть много способов решить эту проблему в WordPress, включая отключение тем и плагинов, восстановление вашего файла .htaccess и сброс ваших постоянных ссылок.

Если у вас возникли какие-либо вопросы, советы или рекомендации по работе с ошибкой WordPress 404 – давайте поговорим о них в разделе комментариев!

Author

Анна долгое время работала в сфере социальных сетей и меседжеров, но сейчас активно увлеклась созданием и сопровождением сайтов. Она любит узнавать что-то новое и постоянно находится в поиске новинок и обновлений, чтобы делиться ими с миром. Ещё Анна увлекается изучением иностранных языков. Сейчас её увлёк язык программирования!

I’ve got a 404 no found on all pages except the homepage in my wordpress.

It didn’t make this mistake on the pre-production server, but in production. I migrated the site from preprod to prod with duplicator’s plugin.

The production server is a vps ovh that I installed myself. It use letsencrypt for https. It uses a ufw firewall and openSSH and WWW Full are allowed. My apache server does not detect an error with sudo systemctl status apache2.

I’ve been following some topics on it, like changing the permalinks settings, when I check «Default» and save, I don’t get error 404 on my other pages, it works. I noticed that in this case the content of my .htaccess file was erased. When I reset my default permalinks settings, I get the error again and I can no longer access my pages (except the homepage).

In the general settings of wordpress, the web address of wordpress is https://www.abysolutions.com and the web address of the site is https://www.abysolutions.com. In wp_options table, the values of siteurl and home are https://www.abysolutions.com.

On ovh in the area dns my domain abysolutions.com has this entry: A 146.59.234.157. However, there is no A entry for www.abysolutions.com.

Here are some configuration files :

/etc/www/apache2/sites-available/abysolutions.conf :

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName abysolutions.com
    ServerAlias www.abysolutions.com
    DocumentRoot /var/www/abysolutions

    <Directory /var/www/abysolutions>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/abysolutions-error.log
    CustomLog ${APACHE_LOG_DIR}/abysolutions-access.log combined
RewriteEngine on
RewriteCond %{SERVER_NAME} =abysolutions.com [OR]
RewriteCond %{SERVER_NAME} =www.abysolutions.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

This file is enabled with sudo a2ensite abysolutions.conf.
I disabled default file sudo a2dissite 000-default.conf.

My .htaccess on /var/www/abysolutions : (when my permaliens settings in enabled)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I did sudo chown -R www-data:www-data /var/www/abysolutions and sudo chmod -R 755 on it.

I restarted the server with sudo systemctl reload apache2 and the rewrite mod is activated with sudo a2enmod rewrite.

I installed all the php extensions required for wordpress by following this link : https://wordpress.org/support/topic/which-php-extensions-are-needed-to-run-a-fully-operational-wordpress-site/

But it still doesn’t work…

It’s not the first time I install a vps and put a wordpress on it, and I always do the same steps. And then for some reason it gets stuck. The only noticeable difference I see with my previous installations is that when I migrated the site with Duplicator it offered me https://www.example.com instead of https://example.com in my previous installations. What I don’t understand is why my url appears with www.

EDIT :

In the health of the site, I noticed 2 critical errors :

An active PHP session has been detected:
A PHP session was created by a session_start() function call. This interferes with the REST API and loopback requests. The session should be closed by session_write_close() before making any HTTP requests.

and

Your site was unable to complete the closure request:
Looping requests are used to launch scheduled events, and by theme and extension editors to check the stability of the code.

The loopback request on your site failed, which means that the features that rely on these requests are not currently working as they should.
Error: cURL error 28: Operation timed out after 10001 milliseconds with 0 bytes received (http_request_failed)

And in the recommended improvements :

The REST API encountered an unexpected result:
The REST API is one way for WordPress or other applications to communicate with the server. An example is the editor’s screen, which is used to display and save your publications.

The call to the REST API returned the following unexpected result: (404) 404 Not Found Not Found

The requested URL was not found on this server.

Apache/2.4.38 (Debian) Server at www.abysolutions.com Port 443

Background updates may not work properly:
Unable to confirm if the wp_version_check() filter is available.

EDIT 2 :

So by comparing my .htaccess with the one of my preproduction server, I noticed that some rules added by the SimpleSSL plugin were missing. I also noticed that in my /etc/apache2/sites-available/abysolutions-le-ssl.conf file, the rules were missing.

I think it is this last solution that corrected my error. Bye!

I’ve got a 404 no found on all pages except the homepage in my wordpress.

It didn’t make this mistake on the pre-production server, but in production. I migrated the site from preprod to prod with duplicator’s plugin.

The production server is a vps ovh that I installed myself. It use letsencrypt for https. It uses a ufw firewall and openSSH and WWW Full are allowed. My apache server does not detect an error with sudo systemctl status apache2.

I’ve been following some topics on it, like changing the permalinks settings, when I check «Default» and save, I don’t get error 404 on my other pages, it works. I noticed that in this case the content of my .htaccess file was erased. When I reset my default permalinks settings, I get the error again and I can no longer access my pages (except the homepage).

In the general settings of wordpress, the web address of wordpress is https://www.abysolutions.com and the web address of the site is https://www.abysolutions.com. In wp_options table, the values of siteurl and home are https://www.abysolutions.com.

On ovh in the area dns my domain abysolutions.com has this entry: A 146.59.234.157. However, there is no A entry for www.abysolutions.com.

Here are some configuration files :

/etc/www/apache2/sites-available/abysolutions.conf :

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    ServerName abysolutions.com
    ServerAlias www.abysolutions.com
    DocumentRoot /var/www/abysolutions

    <Directory /var/www/abysolutions>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/abysolutions-error.log
    CustomLog ${APACHE_LOG_DIR}/abysolutions-access.log combined
RewriteEngine on
RewriteCond %{SERVER_NAME} =abysolutions.com [OR]
RewriteCond %{SERVER_NAME} =www.abysolutions.com
RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent]
</VirtualHost>

This file is enabled with sudo a2ensite abysolutions.conf.
I disabled default file sudo a2dissite 000-default.conf.

My .htaccess on /var/www/abysolutions : (when my permaliens settings in enabled)

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

I did sudo chown -R www-data:www-data /var/www/abysolutions and sudo chmod -R 755 on it.

I restarted the server with sudo systemctl reload apache2 and the rewrite mod is activated with sudo a2enmod rewrite.

I installed all the php extensions required for wordpress by following this link : https://wordpress.org/support/topic/which-php-extensions-are-needed-to-run-a-fully-operational-wordpress-site/

But it still doesn’t work…

It’s not the first time I install a vps and put a wordpress on it, and I always do the same steps. And then for some reason it gets stuck. The only noticeable difference I see with my previous installations is that when I migrated the site with Duplicator it offered me https://www.example.com instead of https://example.com in my previous installations. What I don’t understand is why my url appears with www.

EDIT :

In the health of the site, I noticed 2 critical errors :

An active PHP session has been detected:
A PHP session was created by a session_start() function call. This interferes with the REST API and loopback requests. The session should be closed by session_write_close() before making any HTTP requests.

and

Your site was unable to complete the closure request:
Looping requests are used to launch scheduled events, and by theme and extension editors to check the stability of the code.

The loopback request on your site failed, which means that the features that rely on these requests are not currently working as they should.
Error: cURL error 28: Operation timed out after 10001 milliseconds with 0 bytes received (http_request_failed)

And in the recommended improvements :

The REST API encountered an unexpected result:
The REST API is one way for WordPress or other applications to communicate with the server. An example is the editor’s screen, which is used to display and save your publications.

The call to the REST API returned the following unexpected result: (404) 404 Not Found Not Found

The requested URL was not found on this server.

Apache/2.4.38 (Debian) Server at www.abysolutions.com Port 443

Background updates may not work properly:
Unable to confirm if the wp_version_check() filter is available.

EDIT 2 :

So by comparing my .htaccess with the one of my preproduction server, I noticed that some rules added by the SimpleSSL plugin were missing. I also noticed that in my /etc/apache2/sites-available/abysolutions-le-ssl.conf file, the rules were missing.

I think it is this last solution that corrected my error. Bye!

Просмотр 15 ответов — с 1 по 15 (всего 18)

  • Вероятно какой-то плагин портит файл htaccess.

    Файла htaccess нет. Сайт работает без него.

    Ну, как видим, без него сайт не особо работает — «начинает выдавать 404 ошибку»

    Теперь есть и htaccess файл и все равно периодически весь сайт падает и на всех страницах 404 ошибка.
    Есть может идеи как отследить источник?
    Что вообще в теории может вызывать такие проблемы?

    Модератор
    Yui

    (@fierevere)

    ゆい

    в теории — какой-нибудь конфликтный плагин, создающий свою таксономию.

    Установите тестовый WordPress в отдельной папке с новой базой и создайте пару страниц и записей. Если там тоже будет 404, значит дело в хостинге.

    Ничего не помогает. Ошибка возникает.

    Но вот что заметил.
    Ошибка начала появляться, когда на сайт посыпался спам в виде спам топов на форуме (bbPress). Какие-то китайские боты заспамили весь форум. Я все почистил и поставил защиту от спама (Google captcha на регистрацию, Akismet Anti-Spam).
    Но в отчете по 404 ошибкам я вижу что теперь постоянно возникают запросы к этим удаленным топикам от ботов.
    Так вот. Как можно заблочить доступ к сайту для ботов? И возможно что из-за атак этих ботов весь сайт падает в 404 ошибку?

    Мой сайт спасает от ботов этот плагин https://ru.wordpress.org/plugins/blackhole-bad-bots/

    В настройках плагина в списке разрешенных ботов следует оставить только Яндекс и Гугл боты.

    В настройках плагина в списке разрешенных ботов следует оставить только Яндекс и Гугл боты.

    ага — спам боты прям спецом подписываются в user agent как «Spam Bot».
    вам самому не смешно?
    спам боты маскируются под настоящих людей и user agent подсовывают от браузера.

    Не знаю, как автору плагина это удалось, но теперь сайт не виснет из-за ботов. Там на каждой странице сайта создается ссылка, невидимая для людей, но видимая для ботов. Как бот туда зайдет, так и не выйдет. 🙂

    Модератор
    Yui

    (@fierevere)

    ゆい

    в теории — какой-нибудь конфликтный плагин, создающий свою таксономию.

    Установите тестовый WordPress в отдельной папке с новой базой и создайте пару страниц и записей. Если там тоже будет 404, значит дело в хостинге.

    Ничего не помогает. Ошибка возникает.

    Но вот что заметил.
    Ошибка начала появляться, когда на сайт посыпался спам в виде спам топов на форуме (bbPress). Какие-то китайские боты заспамили весь форум. Я все почистил и поставил защиту от спама (Google captcha на регистрацию, Akismet Anti-Spam).
    Но в отчете по 404 ошибкам я вижу что теперь постоянно возникают запросы к этим удаленным топикам от ботов.
    Так вот. Как можно заблочить доступ к сайту для ботов? И возможно что из-за атак этих ботов весь сайт падает в 404 ошибку?

    Мой сайт спасает от ботов этот плагин https://ru.wordpress.org/plugins/blackhole-bad-bots/

    В настройках плагина в списке разрешенных ботов следует оставить только Яндекс и Гугл боты.

    В настройках плагина в списке разрешенных ботов следует оставить только Яндекс и Гугл боты.

    ага — спам боты прям спецом подписываются в user agent как «Spam Bot».
    вам самому не смешно?
    спам боты маскируются под настоящих людей и user agent подсовывают от браузера.

    Не знаю, как автору плагина это удалось, но теперь сайт не виснет из-за ботов. Там на каждой странице сайта создается ссылка, невидимая для людей, но видимая для ботов. Как бот туда зайдет, так и не выйдет. 🙂

    Модератор
    Yui

    (@fierevere)

    ゆい

    Не знаю, как автору плагина это удалось

    https://ru.wikipedia.org/wiki/Honeypot

    Проблема так и не решилась. Роботов лишних я отрубил. Но сайт все равно периодически уходит в 404 ошибку, которая решается просто пересохранением Permalinks.

    Но заметил такую штуку, сайт ложится когда активность на нем появляется. Но не могу понять почему. Ладно бы сервер ложился из-за перегрузки. Но почему сайт ложится в 404? В ВП есть какие-то ограничения?

    Модератор
    Yui

    (@fierevere)

    ゆい

    в WP ограничений нет.
    Или проблема в хостинге
    или какой-то плагин дурит таким образом. Мб. плагин «безопасности», мб кеша, мб связанный с редиректами или добавлением новых таксономий (галереи например)

    В панели управления хостингом показывают потребление процессора, памяти, количество процессов? Какой хостинг, если не секрет?

    digitalocean

    С нагрузкой вроде справляется.

    Получается можно выявить только методом тыка отключая по очереди плагины и ждать?

  • Просмотр 15 ответов — с 1 по 15 (всего 18)

    Ошибка 404Yui

    (@fierevere)

    ゆい

    в WP ограничений нет.
    Или проблема в хостинге
    или какой-то плагин дурит таким образом. Мб. плагин «безопасности», мб кеша, мб связанный с редиректами или добавлением новых таксономий (галереи например)

    В панели управления хостингом показывают потребление процессора, памяти, количество процессов? Какой хостинг, если не секрет?

    digitalocean

    С нагрузкой вроде справляется.

    Получается можно выявить только методом тыка отключая по очереди плагины и ждать?

    Просмотр 15 ответов — с 1 по 15 (всего 18)

    Источник
    Ошибка 404

    Ошибка 404 — страница не найдена (error 404 page not found)

    Ошибка 404 (Error 404) – это кодовый заголовок ответа HTTP браузеру о статусе HTML-документа, который сообщает, что сервер не обнаружил запрошенную программой-клиентом веб-страницу. Цифровой код «404», как правило, сопровождается сообщением «Страница не найдена» («Not Found»), реже – подробным объяснением причины возникновения ошибки.

    страница 404 ошибки

    Код статуса обозначается тремя цифрами в определенной последовательности:

    • первая указывает на класс состояния. В данном случае «4хх» говорит об ошибке браузера (Client Error) – неправильно вбитом урле сайта в поле адресной строки либо отсутствии страницы на сервере;
    • вторая – «0» – подразумевает ошибку синтаксиса протокола, принадлежность к группе ошибок «40х»;
    • третья цифра в статус-коде «404» конкретизирует ошибку клиента – документ по указанному адресу не найден.

    Иными словами, ошибка 404 сообщает пользователю, что сервер обнаружен, но разыскать запрашиваемую страницу не удалось, нет информации об указанной в браузере странице.

    Национальные домены России со скидкой — домен RU, домен РФ.

    Почему возникает ошибка 404, что означает

    Подоплеки появления ошибки 404 выделяют разные. Она возникает в тех случаях, когда:

    • посетитель неверно ввел адрес веб-ресурса;
    • URL страницы переписали, но битая ссылка осталась на сторонних ресурсах либо в закладках браузера;
    • имя файла на сервере и в коде не совпадают;
    • страницу переместили или вовсе удалили с сайта.

    В редких случаях в качестве исключения сообщение «Ошибка 404» появляется, когда сервер работает некорректно, ресурс атакован вирусом.

    Как исправить 404 ошибку на чужом сайте

    Для пользователей, которые столкнулись с этим явлением на чужом сайте, руководство к действию следующее:

    действия при 404 ошибке

    1. Проверить url в адресной строке на наличие опечаток, попробовать ввести адрес заново.
    2. Перезагрузить не обнаруженную страницу.
    3. Вернуться на предыдущую страницу и снова совершить попытку зайти на нужную.

    Сервисы, помогающие найти и устранить 404 ошибки

    На своем сайте вебмастер использует несколько методов, чтобы определить несуществующие страницы, битые ссылки.

    Google Webmasters (консоль для вебмастеров гугл)

    поиск 404 в гугл серч консоли

    В диагностике применяют инструменты для вебмастеров от гугл. Для этого:

    1. Переходят в панель инструментов.
    2. Выбирают адрес сайта.
    3. В левом поле находят строку «Сканирование» и раскрывают список.
    4. В списке выбирают опцию «Ошибки сканирования».
    5. В правом поле под заголовком «Ошибки URL» выбирают закладку «ПК».
    6. Уровнем ниже в закладке «Не найдено» будет указано количество страниц с ошибкой 404.
    7. Далее следует развернутый список тех страниц, на которых обнаружили ошибку.
    8. Отредактировав ошибки, страницы отмечают чекером.
    9. Жмут на кнопку «Отметить как исправленные».

    Яндекс.Вебмастер

    Подобным образом пользуются сервисом Яндекс.Вебмастер. Для анализа выполняют такие действия:

    поиск 404 в яндекс вебмастере

    1. На главной странице выбирают опцию «Добавить сайт».
    2. В появившейся строке вводят URL ресурса.
    3. После добавления в левом поле выбирают в меню строку «Индексирование сайта»(Индексация сайта Яндексом может длиться несколько недель, метод подходит, если сайт уже добавлен и нужно найти ошибки 404).
    4. Из выпавшего списка выбирают опцию «Исключенные страницы».
    5. Результаты анализа размещаются ниже в виде списка несуществующих страниц.

    Xenu’s Link Sleuth

    Кроме популярных онлайн-сервисов проверить сайт на наличие битых ссылок возможно с использованием программ. С этой целью применяют бесплатную программу Xenu’s Link Sleuth. Вместе с битыми ссылками Xenu находит страницы, на которых подобные линки сохранились. Порядок действий следующий:

    поиск 404 в xenu Link Sleuth

    1. На панели меню выбирают кнопку «File».
    2. В открывшемся списке нажимают «Check URL».
    3. В верхней строке появившегося окна вводят домен.
    4. Когда сайт просканировался, в результатах красным цветом выделяются адреса страниц с ошибкой и статусом «not found».
    5. Чтобы выяснить, где размещаются ссылки на ненайденные страницы, красные линки выделяют, щелкают по ним правой клавишей мыши и выбирают операцию «URL properties».

    После того, как Вы нашли 404 ошибки — их нужно устранить. Для этого следует или поправить битые ссылки (в случае опечатки), или настроить перенаправления (в случае, если страница была перемещена по другому адресу).

    На нашем хостинге страницы Вашего ресурса не потеряются! Стоимость виртуального хостинга сайтов.

    Влияние ошибки 404 на SEO

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

    Необходимо, чтобы подобные ошибки имели верный код заголовка «404» ответа HTTP о статусе страницы. Поисковые машины, переходя по ссылкам, в первую очередь анализируют код. Неверный заголовок ответа плохо отражается на продвижении сайта.

    Сглаживание негатива от ошибки 404 на посетителя — оформление страницы картинками, ссылками

    Наряду с этим нельзя забывать о реакции пользователя, который вместо страницы с нужной информацией получает пустой документ с сообщением об ошибке 404. Здесь необходимо побудить посетителя остаться на сайте и направить действия в нужном направлении. Для этого уделяют внимание:

    • дизайну странице в стиле сайта;
    • присутствию элементов навигации, которые помогут сориентироваться и перенаправить посетителя;
    • наличию списка популярных страниц ресурса.

    полезная страница в стиле сайта

    Такой подход – продуманно оформленная страница с подсказками – поможет задержать посетителя на сайте, а не уйти раз и навсегда в поисках нужной информации на другие ресурсы.

    К оформлению этой страницы нужен ответственный подход, как и к дизайну главной, контактам и прочей полезной информации. Она не должна выглядеть примитивно и выбиваться из стиля сайта:

    • если дизайн ресурса строгий, страница с сообщением об ошибке 404 также должна отражать основную концепцию сайта;
    • для сайтов развлекательного направления применяют оригинальные привлекающие внимание картинки, мультимедийные элементы, Flash-анимацию – здесь уместно использовать юмор.

    залипни на странице ошибки

    Чтобы посетитель не закрыл страницу сразу, посетителя отвлекают визуальными эффектами, добавляют интерактивные компоненты, чтобы пользователь заинтересовался. Творческие идеи по оформлению страницы помогут с нивелировать резко отрицательное впечатление пользователя, обратив разочарование ошибкой в приятный сюрприз. Однако рекомендуется избегать перегруженных тяжеловесных страниц – они должны загружаться с приемлемой скоростью.

    Важно оставить хорошее впечатление после столкновения с ошибкой и завязать диалог с потенциальным клиентом, пользователем услуг сайта, покупателем. Как правило, посетитель покидает ресурс, если ошибка 404 заставляет растеряться, и он не знает, как действовать дальше.

    Обернуть этот казус в пользу можно в том случае, если страницу сделают практичной, полезной. Чтобы направить посетителя в верном направлении, используют следующие приемы:

    1. Кроме стандартного сообщения, что страница не найдена, составляют доброжелательно обращение к пользователям, что введенный адрес набрали с ошибкой, и посоветовать перепроверить URL. Кроме того, пользователь найдет необходимую информацию, воспользовавшись поиском или вернувшись на главную страницу сайта.
    2. На странице с сообщением об ошибке оставляют нужные элементы навигации: главное меню, сайдбар, футер, поле для поиска.
    3. Оставляют ссылки на популярные страницы или последние записи сайта с предложением ознакомиться с ними.
    4. Полезно дать посетителю шанс сообщить об обнаруженной ошибке, битой ссылке нажатием одной кнопки. Это поможет веб-мастеру улучшить сайт, а пользователю даст почувствовать, что его мнение ценят, а действие – полезно для ресурса.
    5. Помимо прочего, здесь размещают координаты для обратной связи.

    CMS WordPress и Ошибка 404

    Ошибка 404 – распространенная проблема, которая возникает у неопытных пользователей CMS WordPress. Чаще при этом не ограничивается доступ к админ-панели, загружается главная страница, но при переходе по ссылкам на вложенные страницы появляется сообщение об ошибке 404. Такое случается, когда удаляют Htaccess файл либо некорректна работа правил перезаписи. Чтобы исправить положение, обновляют параметры постоянных ссылок.

    Причинами появления сообщения об ошибке 404 служат также:

    • изменение структуры ссылок;
    • переименование страниц;
    • битые ссылки.

    Они возникают, когда существовавшая прежде страница удаляется, но ссылка на нее остается на посторонних сайтах. Проверить наличие мертвых ссылок ресурса на движке WordPress можно при помощи плагина Broken Link Checker. Для этого плагин устанавливают на сайт. Программу требуется активировать. После этого в консоли под кнопкой «Инструменты» в списке появляется опция «Неправильные ссылки». Статус страницы указывается в столбце «Состояние».

    CMS Joomla и Ошибка 404

    В CMS Joomla создана отдельная страница для сообщения об ошибке 404, дизайн которой одинаков во всех шаблонах. Поэтому потребуется уделить время, чтобы вписать оформление в общий вид сайта, добавить элементы навигации главного меню. Для этого:

    1. Заходят в административную панель.
    2. Создают новый материал с подходящим названием. Логичным выбором станет: «Ошибка 404. Страница не найдена».
    3. В материале пишут сообщение для пользователя с разъяснением причин ошибки и рекомендациями что делать.
    4. При желании оставляют ссылки на иные разделы или поисковую строку.

    Версии Joomla отличаются тонкостями в настройках страницы:

    • в Joomla 2.5, 3.0 в настройках материала из списка под кнопкой «Категория» выбирают опцию «Uncategorised»;
    • в версии Joomla 1.5 в списке «Раздел» и «Категория» из раскрывшегося перечня выбирают «Не указанно».

    iPipe – надёжный хостинг-провайдер с опытом работы более 15 лет.

    Мы предлагаем:

    • Виртуальные серверы с NVMe SSD дисками от 299 руб/мес
    • Безлимитный хостинг на SSD дисках от 142 руб/мес
    • Выделенные серверы в наличии и под заказ
    • Регистрацию доменов в более 350 зонах
    Источник

    Если главная страница сайта отображается, а внутренние выдают ошибку 404 или 500, проблема заключается в отсутствии файла .htaccess или его неправильном содержании.

    Внутренние страницы перестают открываться на CMS (WordPress, Joomla, DLE), поскольку в этих системах файл .htaccess имеет большое значение и часто видоизменяется. Проблема появляется при переносе сайта с одного виртуального хостинга на другой.

    Оглавление статьи:

    • Причины и решение ошибки 404/500
    • Файл .htaccess для WordPress
    • Хостинг на Windows и панель ISPmanager

    Причины и решение ошибки 404/500

    Файл .htaccess должен содержать записи, необходимые для работы CMS. При переносе сайта на новый хостинг, особенно через браузерные версии панелей хостеров, данный файл может не попасть в архив из-за настроек безопасности. Как следствие, на новом хостинге файла не будет, и правильно развернутая из бекапа и настроенная CMS работать не будет — кроме главной страницы. Наиболее часто проблема наблюдается на сайтах, где вместо стандартного отображения URL подключено ЧПУ.

    Внутренние страницы перестают открываться, если:

    1. Файл .htaccess отсутствует. Проблема актуальна при переносе сайта с одного хостинга на другой.
    2. Файл пустой. Содержимое файла может быть удалено по ошибке, в результате заражения сайта вирусами или по иной причине.
    3. Содержимое файла изменено или повреждено. Если внутренние страницы сайта перестали работать после каких-либо действий с .htaccess, следует проверить файл на наличие всех директив, необходимых для работы CMS.

     Страница 404 WordPress

    Отличительной особенностью ошибки с файлом .htaccess является измененный дизайн страницы 404/500. Страницы ошибки 404 будут отдаваться сервером и отличаться от оформления 404 у сайта (с шаблоном и дизайном, элементами навигации). Актуально, по крайней мере, для WordPress.

    Для исправления ошибок нужно создать .htaccess с нужным содержимым. Содержание файла будет меняться в зависимости от CMS. Помимо указанного кода, в файле может содержаться любая информация и директивы, необходимые для функционирования сайта.

    Файл .htaccess для WordPress

    Каждая система управления контентом требует определенных директив для полноценного и корректного функционирования. Документ .htaccess должен располагаться в корне сайта и иметь, как минимум, указанное ниже содержание (для WordPress).

    # BEGIN WordPress

    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    # END WordPress

    Содержимое файлов для других популярных CMS можно без проблем найти в сети — там текста в разы больше, и в статью информация попросту бы не влезла. У WordPress содержимое файла не менялось годами, а потому ошибка одинаково хорошо решается на всех версиях движка.

    Хостинг на Windows и панель ISPmanager

    Любые операции с файлом .htaccess актуальны только для хостингов, расположенных на Linux-серверах. Сервера от Windows попросту не имеют такого файла — вместо него аналогичные функции выполняются в документе web.config. Уточнять содержимое данного файла следует в поддержке соответствующей CMS.

    Помимо этого, проблема с ошибкой 404 на внутренних страницах актуальна для Linux-серверов с панелями ISPmanager. В этом случае требуется отключить автоподдомены, если они включены, и проверить наличие проблемы. Ошибки 404 и 500 могут исчезнуть и без замены .htaccess (либо с файлом изначально все нормально, если он присутствует в корне и правильно заполнен).

    Источник

    All of a sudden I go to my WordPress website and all the pages give me a 404 page not found page. I’m assuming the problem lies with the permalink structure, which I could swear I did not touch. The permalink setting is on «month and name.»

    I’ve researched similar instances of this problem online and a lot of it has to do with the .htaccess file? I tried finding, but I can’t. Perhaps it got deleted somehow? Where is it supposed to be located.

    Any suggestions will be helpful

    and of course I can see hidden files.

    Marc's user avatar

    Marc

    4,6113 gold badges39 silver badges62 bronze badges

    asked Mar 3, 2011 at 15:07

    Adam's user avatar

    2

    .htaccess is a hidden file, so you must set all files as visible in your ftp.

    I suggest you return your permalink structure to default ( ?p=ID ) so you ensure that .htaccess is the problem.

    After that, you could simply set «month and name» structure again, and see if it works.

    PS: Have you upgraded to 3.1? I’ve seen some people with plugin issues in this case.

    answered Mar 3, 2011 at 15:18

    Rochester Oliveira's user avatar

    9

    Basically the .htaccess file should exists and the httpd.conf should be correct.

    In my case, I changed the file /etc/apache2/apache2.conf in section:

    <Directory "/var/www/html">
    

    Line changed is:

    AllowOverride None
    

    to

    AllowOverride All
    

    And restart the web server with

    systemctl restart apache2
    

    Community's user avatar

    answered Sep 9, 2016 at 4:52

    georgeos's user avatar

    georgeosgeorgeos

    2,3412 gold badges24 silver badges28 bronze badges

    5

    Fixing that problem is very simple if you was using permalinks other than the default such as Day and name, Month and name, Numeric, Post name or Custom Structure, you only need to

    Login to your admin area: Settings > Permalinks which should be : http://yoursite.com/wp-admin/options-permalink.php

    Choose Default permalink setting, then save changes

    Then you can return it again to your other previous permalink choice or keep it as default as yo wish

    Note that this problem can happen when you move your site from a domain or location to another one.

    answered Sep 27, 2013 at 19:59

    usama sulaiman's user avatar

    usama sulaimanusama sulaiman

    2,0033 gold badges24 silver badges37 bronze badges

    8

    If the default behavior (example.com/?p=42) is working, you should:

    • Change to your preferred permalink style: Admin: Settings > Permalinks, and click Save. Sometime it fixes the issue. If it didn’t:
    • Verify that the file /path/to/wordpress/.htaccess has been changed and now includes the line RewriteEngine On. If it doesn’t include the line, it’s a WordPress permissions issue.
    • Verify that the ‘rewrite’ module is loaded: create a PHP file with

      <?php
        phpinfo()
      ?>
      

      in it, open it in the browser and search for mod_rewrite. It should be in the ‘Loaded Modules’ section.
      If it’s not, enable it — Look at your apache default index.html file for details — in Ubuntu, you do it with the helper a2enmod.

    • Verify that apache server is looking at the .htaccess file. open httpd.conf — or it’s Ubuntu’s alternative, /etc/apache2/apache2.conf. In it, You should have something like

      <Directory /path/to/wordpress>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
      </Directory>
      
    • After making these changes, don’t forget to restart your apache server. sudo service apache2 restart

    RyanS's user avatar

    RyanS

    6271 gold badge10 silver badges26 bronze badges

    answered Jan 30, 2017 at 2:06

    tsvikas's user avatar

    tsvikastsvikas

    15.7k1 gold badge21 silver badges11 bronze badges

    0

    IF all this dont work, your .htaccess is correct, and permalinks trick didnt work, you may have not enabled your apache2 rewite mod.

    I ran this and my issue was solved:

     sudo a2enmod rewrite 
    

    answered Feb 20, 2018 at 18:06

    David Valenza's user avatar

    2

    Within the WordPress admin interface do the following:

    1. Go to admin setting

    2. Click on permalink and select post name in radio button.

    3. Scroll down and you will see .htaccess code here like.

      <IfModule mod_rewrite.c>
          RewriteRule ^index.php$ - [L]
          RewriteCond %{REQUEST_FILENAME} !-f
          RewriteCond %{REQUEST_FILENAME} !-d
          RewriteRule . /wordpress/index.php [L]
      </IfModule> 
      
    4. Copy the code and paste in the .htaccess file.

    Blackbam's user avatar

    Blackbam

    17.2k24 gold badges97 silver badges150 bronze badges

    answered Mar 14, 2014 at 10:24

    Mahesh singh chouhan's user avatar

    3

    This error is causing due to disabled of rewrite mod in apache httpd.conf document ,just uncomment it and enjoy the seo friendly permalinks

    answered Apr 5, 2013 at 22:34

    Asif Khan's user avatar

    Asif KhanAsif Khan

    811 silver badge1 bronze badge

    • Check that the directory on .htaccess are the correct
    • Check the fields «siteurl» and «home» are the correct

    answered Mar 4, 2011 at 7:07

    José Carlos's user avatar

    José CarlosJosé Carlos

    1,00516 silver badges29 bronze badges

    1

    We had the same problem and solved it by checking the error.log of our virtual host. We found the following message:

    AH00670: Options FollowSymLinks and SymLinksIfOwnerMatch are both off,
    so the RewriteRule directive is also forbidden due to its similar
    ability to circumvent directory restrictions :
    /srv/www/htdocs/wp-intranet/

    The solution was to set Options All and AllowOverride All in our virtual host config.

    answered Jul 3, 2018 at 14:48

    Black's user avatar

    BlackBlack

    17.7k39 gold badges155 silver badges268 bronze badges

    If you have FTP access to your account:

    First, login to your wp-admin and go to Settings > Permalinks

    You should see something at the bottom that says:

    «If your .htaccess file were writable, we could do this automatically, but it isn’t so these are the mod_rewrite rules you should have in your .htaccess file. Click in the field and press CTRL + a to select all.»

    If this is true do the following:

    1. Go into preferences for your FTP client and make sure hidden files are displayed (varies depending on your FTP client) — If you don’t do this you won’t be able to find your htaccess file

    2. Go to the folder that your wp-admin, wp-content, wp-includes directories are located. Check for .htaccess file. If it exists skip to step 4

    3. If it does not exist, create a new blank file in your FTP program called .htaccess

    4. Change the CHMOD for your .htaccess file to 666 (your preference on how you want to do this)

    5. Go back to your Permalinks page and edit the link structure you want. Problem should be solved!

    6. Make sure to change the chmod of the htaccess file back to 644 after you are done.

    Just had the same problem and it seemed to fix it instantly! Good luck!

    answered Oct 12, 2012 at 16:47

    JEFF B's user avatar

    JEFF BJEFF B

    1262 silver badges12 bronze badges

    1

    Most of the time this issue is fixed by simply visiting the Settings -> Permalink page in the WordPress admin and click Save (as several other answers already pointed out). When this page is accessed, WordPress rewrites the directives in the .htaccess file which magically fixes the issue. The issue often happens after moving a site (the site breaks because the .htaccess gets left behind or the settings need to be updated).

    If WordPress doesn’t have the right permissions to write the .htaccess file, a notice will appear at the top of the page and further instructions at the bottom when the settings are saved. In this case you need to edit the .htaccess file yourself or, better, to fix the permissions on that file. The file is at the root of the WordPress installation. cd into the directory and sudo chmod 644 .htaccess. You might also want to check if the file belongs to the right group and change that is needed with chown. Ask your hosting provider if you don’t know how to do that.

    If you are on shared hosting that’s probably all you can do. If you still have the issue you might want to talk to you hosting provider’s support. Otherwise, make sure the use of .htaccess files is enabled on the server, as @georgeos already suggested. Note that httpd.conf is not always used (Ubuntu indicates it is deprecated but the official Apache docs still says it is often the main configuration file). /etc/httpd/conf/httpd.conf and /etc/apache2/apache2.conf seem to be the most common places for this file. Find the block for the public folder, usually <Directory /var/www/> and make sure that the AllowOverride directive is set to All. If it is set to None, your .htaccess file is simply ignored by the server.

    answered Aug 15, 2017 at 23:45

    mrtnmgs's user avatar

    mrtnmgsmrtnmgs

    1,36313 silver badges26 bronze badges

    You may have .htaccess disallowed in webhost settings.
    Setting to default permalinks would work in that case.

    answered Feb 28, 2017 at 14:34

    Fanky's user avatar

    FankyFanky

    1,6231 gold badge18 silver badges20 bronze badges

    Before trying to do any permalink or server config changes, please check you .htaccess file. This mostly is a corrupt or blank .htaccess file issue. Reset the htaccess file to the default

    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
    # END WordPress
    

    answered Mar 15, 2019 at 11:37

    Mustafa sabir's user avatar

    Mustafa sabirMustafa sabir

    4,1301 gold badge19 silver badges28 bronze badges

    0

    Case 1:- Let us think if migrate site from one hosting to another hosting if see this kind of issue.

    Solution:- Simply go to old server copy .htaccess file code, then past in new server .htaccess file. 99% it i will works.

    answered Nov 7, 2017 at 5:05

    Navruk's user avatar

    NavrukNavruk

    9276 gold badges17 silver badges29 bronze badges

    after 2 long days,
    the solution was to add options +FollowSymLinks to the top of my .htaccess file.

    answered Apr 4, 2020 at 2:29

    Ahmad Ali's user avatar

    Ahmad AliAhmad Ali

    6941 gold badge10 silver badges28 bronze badges

    Go to your WordPress Dashboard, scroll down to settings, select Permalink,

    in custom settings that appear, go to custom structure and replace the text in the text field with

    /index.php/%year%/%monthnum%/%day%/%postname%/
    

    and then save changes

    answered Jul 7, 2021 at 14:42

    Insookwa's user avatar

    InsookwaInsookwa

    891 silver badge5 bronze badges

    This scenario can also be caused by a database version that’s out of sync with the WP files installed on server. Nothing else listed here worked for me; I solved it with a manual WP update.

    answered Nov 1, 2022 at 20:40

    Blorf's user avatar

    BlorfBlorf

    5263 silver badges12 bronze badges

    I have the same problem and so I remove the Apache and make it again and the problem was solved.

    answered Jun 6, 2013 at 16:38

    boomz's user avatar

    boomzboomz

    6575 silver badges21 bronze badges

    Just Navigate to Settings->Permalink in your dashboard and then Save Changes button in the last.

    answered Jul 13, 2017 at 10:30

    Deepak Sharma's user avatar

    I just changed the permalink to ‘month and day’of all the posts by ging to setting>permalink.

    Now all posts are open and working fine.

    Again, I renamed to all posts to its actual permalink. Its again working fine.

    This method worked for me :-)

    answered May 20, 2018 at 13:57

    Shani Deshwal's user avatar

    For nginx users

    Use the following in your conf file for your site (usually /etc/nginx/sites-available/example.com)

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

    This hands off all permalink requests to index.php with a URI string and supplied arguments. Do a systemctl reload nginx to see the changes and your non-homepage links should load.

    answered Jun 14, 2018 at 14:24

    ABC Taylor's user avatar

    Wanted to share my two cents. Recently came accross that very same issue installing WordPress 5.9. Year 2021.

    Configuration:

    Platform MAC, Software XAMPP, WordPress 5.9

    None of the previous answer did it for me.

    The issue was due to the fact that files permissions accross the XAMPP folder were set to «Read only».

    1. Locate the XAMPP folder. (Usually in the Applications folder).
    2. Right click XAMPP folder.
    3. Get info.
    4. Bottom right unlock button → Follow instructions.
    5. Sharing and permissionsEveryoneRead & Write.
    6. Bottom left three dots button → Apply to enclosed items.

    answered Jan 29, 2022 at 10:39

    amarinediary's user avatar

    amarinediaryamarinediary

    4,8254 gold badges27 silver badges45 bronze badges

    I had this issue not so long ago. I had reset my permalink to default or just saved it, updated themes/core to (4.7.4)/plugins, deactivated all plugins, switched to default theme, optimized database, .htaccess is already default, checked file permissions, mod_rewrite is on.

    So far nothing works, what works are the posts, new page, the /contact page EXCEPT for old pages.

    Basically, the pages/URLs that aren’t working are:

    /breeding
    /training
    /training/*
    /breeding/*
    

    Ultimate, I found these files in the root folder:

    /breeding.php and /training.php

    I renamed both files and the pages above worked.

    answered May 16, 2017 at 16:05

    Loreto Gabawa Jr.'s user avatar

    Источник

    Здравствуйте.
    Я сейчас натягиваю верстку на движок WordPress у себя локально на OpenServer. Внезапно все страницы кроме главной стали отображаться по шаблону 404.php. Я связываю это с тем что в процессе изменил настройки url — я изначально не поменял их на ЧПУ, а когда поменял, видимо возникла эта проблема. Я погуглил, в интернете предлагают решить эту проблему изменением содержимого файла .htaccess и активированием mod_rewrite конфигурации сервера Apache.
    Просто изменение .htaccess не помогло.
    В Apache строка «LoadModule rewrite_module modules/mod_rewrite.so» раскомментирована, и в
    AllowOverride All

    Содержимое .htaccess сейчас такое:
    # BEGIN WordPress

    RewriteEngine On
    RewriteBase /
    RewriteRule ^index.php$ — [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    # END WordPress

    Подскажите, я правильно понимаю свою проблему со страницами, делаю ли я то что надо, и как собственно справиться с проблемой? На хостинг пока не заливал, т.к. до конца не понял в чем тут дело.
    Заранее спасибо.

    Источник

    Понравилась статья? Поделить с друзьями:
  • Ошибка 404 весна не найдена
  • Ошибка 404 компонент не найден
  • Ошибка 404 нет такой страницы если вы считаете что
  • Ошибка 404 ваша страница не найдена
  • Ошибка 404 код ответа http