Search code examples
regexapache.htaccessmod-rewrite

.htaccess RewriteRule to path without changing URL


So, I've this problem:

  1. Base Website located at http://example.com/
  2. Second Website located at http://example.com/web2/
  3. People making various requests to the second website like http://example.com/myWeb/pg1 and http://example.com/web2/pg2

Recently and due to some other issues I need to have a custom new path for the second website but also keep the first one working.

The ideia is to allow users to access the second website over the two following addresses:

  • http://example.com/web2/
  • http://example.com/alternative-url-web2/

The folder /web2/ actually exists on the server, but how can I simulate the folder /alternative-url-web2/ and "redirect" the requests to /web2/?

Please note I don't want the URL on the browser to change, this must be a "silent redirect". And I also make sure that all other requests like http://example.com/other are not redirected by the second website.

Thank you.


Update:

According to @anubhava I could simply solve this issue by adding in my .htaccess:

Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteRule ^alternative-url-web2(/.*|)$ /web2$1 [L,NC]

This is probably working fine but I noticed the following:

  • http://ex.com/alternative-url-web2 is redirected to http://ex.com/web2/ (changing browser URL);
  • http://ex.com/alternative-url-web2/ is redirected to http://ex.com/(changing browser URL);
  • http://ex.com/alternative-url-web2/someRequest works fine and does NOT change the browser URL;
  • http://ex.com/alternative-url-web2/index.php works fine and does NOT change the browser URL;

Site Note:

At /web2/ there's an .htaccess that might be cause the wired redirect behavior above... So here is the file contents:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -l [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^.*$ - [NC,L]
    RewriteRule ^(data/|js/|styles/|install/|favicon\.ico|crossdomain\.xml|robots\.txt) - [NC,L]
    RewriteRule ^.*$ index.php [NC,L]
</IfModule>

Can the internal RewriteRule to index.php be causing all this? If yes, how can I fix it?


Solution

  • Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

    Options +FollowSymLinks -MultiViews
    # Turn mod_rewrite on
    RewriteEngine On
    RewriteBase /
    
    RewriteRule ^alternative-url-web2(/.*|)$ /web2$1 [L,NC]
    

    Alternate code:

    RewriteRule ^alternative-url-web2/?$ /web2/ [L,NC]
    RewriteRule ^alternative-url-web2/(.+)$ /web2/$1 [L,NC]