Use mod_rewrite to redirect from example.com/dir to www.example.com/dir

Suppose / is the root of a document in my example.com domain.

/.htaccess

 RewriteEngine on RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L] 

/dir/.htaccess

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

I know how to redirect example.com/dir to www.example.com/dir because /.htaccess does the job.

However, the trick is that I have to support /dir/.htaccess to serve virtual directories (e.g. /dir/state/AK/35827/ which are not actual directories) if you know what I mean.

The problem is that if I save /dir/.htaccess , the request is:

 http://example.com/dir/state/AK/35827/ 

NOT redirected to:

 http://www.example.com/dir/state/AK/35827/ 

:

 http://example.com/ 

redirect to:

 http://www.example.com/ 

Not sure if I'm clear.

Basically, how to make http://example.com/dir/state/AK/35827/ redirect correctly to http://www.example.com/dir/state/AK/35827/ and I can serve virtual URLs ?

+4
source share
2 answers

If you have access to your Apache VirtualHosts configuration, you need to:

 <VirtualHost *:80> ServerName example.com Redirect permanent / http://www.example.com/ </VirtualHost> 

This will redirect http://example.com/ to http://www.example.com/ and http://example.com/dir/state/AK/35827/ to http://www.example.com / dir / state / AK / 35827 /

+1
source

The "problem" is that mod_rewrite does not "inherit" the parent configuration ( .htaccess ) by default. The mod_rewrite directives in a subdirectory completely override the mod_rewrite directives in the parent directory (unlike other modules).

You either need:

  • Copy the canonical WWW redirect from the parent .htaccess file to /dir/.htaccess . But code duplication is undesirable.

  • OR: Enable mod_rewrite inheritance in the child .htaccess file:

     RewriteOptions inherit 

    This effectively copies mod_rewrite directives from the parent .htaccess file. However, if you have other directives, this may not work as expected. Note that this "copies" the directives without changing the directory prefix.

  • OR: do everything in the parent .htaccess file. The preferred solution is to have a single .htaccess file. For instance:

     RewriteEngine on # Canonical redirect RewriteCond %{HTTP_HOST} ^example\.com$ [NC] RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L] # Virtual directories... RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^dir/ dir/index.php [L] 
0
source

Source: https://habr.com/ru/post/1333391/


All Articles