.htaccessmod-rewritehttp-redirecturl-masking

How to use .htaccess to redirect while maintaining the original URL


I am trying to use the .htacces file to redirect any files or subfolders in a derectory to one file, while still maintaining the original URL input.

So if a user goes to:

https://example.com/folder1/folder2/folder3/
or
https://example.com/folder1/folder2/file.php

it would redirect them back to:

https://example.com/folder1/index.php

but the original URL input would not change.


Solution

  • You can use RewriteRule . In htaccess in the document root add the following rule:

    RewriteEngine on
    RewriteCond %{REQUEST_URI} !^/folder1/index\.php$ [NC]
    RewriteRule ^folder1/.+$ /folder1/index.php [L]
    

    This will redirect /folder1/foo/bar to /folder1/index.php without changing the url in browser.
    The RewriteCond above makes sure you don't rewrite /folder1/index.php to itself (/folder1/index.php) otherwise the rule can cause an infinite loop error.