Enable mod_rewrite Module

The mod_rewrite module is enabled by default on CentOS 7. If you find it is not enabled on your server, you can enable it by editing 00-base.conf file located in /etc/httpd/conf.modules.d/ directory.

sudo nano /etc/httpd/conf.modules.d/00-base.conf
Add or uncomment the following line:

LoadModule rewrite_module modules/mod_rewrite.so

Save and close the file, then restart the httpd service:

sudo systemctl restart httpd
Enable .htaccess File

Once the mod_rewrite module has been activated, you can set up your URL rewrites by creating an .htaccess file in your default document root directory. A .htaccess file allows us to modify our rewrite rules without accessing server configuration files. For this reason, .htaccess is critical to your web server. Before we begin, we need to allow Apache to read .htaccess files located under the /var/www/html directory.

You can do this by editing httpd.conf file:

sudo nano /etc/httpd/conf/httpd.conf

Find the section <directory /var/www/html> and change AllowOverride None to AllowOverride All

<Directory /var/www/html>
AllowOverride All

Save and exit.

Now restart Apache to put the change into effect.


Redirect requests with .htaccess

Redirect “ALL” requests to a domain to a subdirectory

You can redirect all requests to a subdirectory by adding an .htaccess file to the root of your domain’s directory:

  1. Visit the FTP page for instructions on how to upload.
  2. Once connected, upload (or create) a text file named .htaccess (with no extension).
  3. Make sure it’s uploaded to your domain’s directory such as example.com.
  4. Add the following content to this .htaccess file:
RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_URI} !^/blog/

# Rewrites all URLS [Replace "example" with the actual domain, without the TLD (.com, .net, .biz, etc)]
RewriteCond %{HTTP_HOST} ^(www\.)?example\.

# Rewrite all those to insert /folder
RewriteRule ^(.*)$ /blog/$1 [L]


This example redirects all requests for a website automatically to a subdirectory named /blog. If you need to redirect to another directory, just change the two references of /blog to your subdirectory.

Redirect “ONLY” the domain’s root URL to a subdirectory

The following example provides an alternative method of transparently redirecting. It works with any subdomain (including root/naked domains) and only transparently redirects a root request, while allowing directly requested subdirectories like example.com/other to be accessed.

RewriteEngine on
RewriteCond %{HTTP_HOST} example\.com [NC]
RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^(.*)$ /blog/$1 [L]


Redirecting in WordPress

The redirect feature is included in WordPress. Visit their codex page for instructions on Giving WordPress Its Own Directory.