WordPress 404 page not found all pages except homepage

WordPress is the king of web CMS. 30% of the entire web runs on WordPress.

After setting up the WordPress you may see the homepage looks all good but the other pages are not showing up. If we hit other pages it shows 404 pages not found message. Following are the steps to resolve this issue:

To solve this issue we will have to start from the root of this issue. In most cases, WordPress uses apache as a web server. The web server apache prohibits .htaccess file to apply rewrite rules. So at first we will have to modify the apache config to allow rewrite rules using .htaccess.

AllowOverride in apache config

Lets open the apache configuration file. We were using ubuntu so the configuration file was in: /etc/apache2/apache2.conf
It could be here: /etc/httpd/conf/httpd.conf for you.

Now open the configuration file in an editor and look for the following section:

<Directory /var/www/>
        Options FollowSymLinks
        AllowOverride None
        Require all denied
</Directory>

This configuration tells apache not to allow any rewrite rule using .htaccess file. Now replace the above config with the following one:

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

If you can’t find the apache configuration, open your virtual host file and update the virtual host like below:

<VirtualHost *:80>
   <Directory /var/www/>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
   </Directory>

    . . .
</VirtualHost>

Once you are done changing the config restart the apache:

$ sudo service apache2 restart
or
$ sudo /etc/init.d/apache2 restart
or 
$ sudo systemctl restart apache2

Enable mod rewrite for apache

At this point, we are set with apache settings. Now the next things to enable the mod rewrite rules for apache. If you already have mod-rewrite enabled then you can ignore this step:

$ sudo a2enmod rewrite

After you enable the mod rewrite restart the apache:

$ sudo service apache2 restart
or
$ sudo /etc/init.d/apache2 restart
or 
$ sudo systemctl restart apache2

Add a .htaccess file

Now add a .htaccess file inside the DocumentRoot directory. Following is the .htaccess file content.

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

This .htaccess rewrite rule redirects all traffic to an index.php file in the DocumentRoot.

If your DocumentRoot is writable by web server then if you change your permalink settings in WordPress admin, WordPress generates a .htaccess file and solves the issue.