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

93 Views Asked by At

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.

2

There are 2 best solutions below

1
Amit Verma On BEST ANSWER

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.

3
Yassine CHABLI On

You can just make :

RedirectMatch 301 ^https://example.com/folder1/ https://example.com/folder1/index.php

This allows you to redirect from the first url in the pattern to the second one