Francesco2810 Francesco2810 - 4 years ago 216
Apache Configuration Question

.htaccess check if file exists in multiple sub-folders and rewrite

Let's suppose that I have a static website on Apache server with this folders structure:

http://www.example.com
|
+-- /news/
| |
| +-- page1.html
| +-- page2.html
| +-- ...
|
+-- /otherstuff/


The url of the pages inside the /news/ folder is:

http://www.example.com/news/page1.html
http://www.example.com/news/page2.html


Now, the number of files in the /news/ folder is growing and I would like to create new subfolders inside /news/ and split files across these new dirs, but I also want to hide the subfolders names in the urls.

The new folders structure will be:

http://www.example.com
|
+-- /news/
| |
| +-- /subfolder1/
| | |
| | +-- page1.html
| |
| +-- /subfolder2/
| | |
| | +-- page2.html
| +-- ...
|
+-- /otherstuff/


but the urls of the pages have to remain the same:

http://www.example.com/news/page1.html
http://www.example.com/news/page2.html


and not:

http://www.example.com/news/subfolder1/page1.html
http://www.example.com/news/subfolder2/page2.html


Is there a way to achive this result using rewrite rules in .htaccess?

I've read this question:
How to use mod_Rewrite to check multiple folders for a static file

but the accepted answer does not work for me.

Thanks in advance for any advice.

Answer Source

you can use the following rule in /news/.htaccess :

RewriteEngine on

RewriteCond %{DOCUMENT_ROOT}/subfolder/$1.html -f
RewriteRule ^(.*?)\.html$ /news/subfolder/$1 [L]

This will rewrite /news/file.html to /news/subfolder/file.html if file.html exists in /news/subfolder/ .

If your htaccess is in root, you can try the following

RewriteEngine on

RewriteCond %{DOCUMENT_ROOT}/news/subfolder/$1.html -f
RewriteRule ^news/(.*?)\.html$ /news/subfolder/$1.html [L]

If the examples above fail, you can try this in root or news/.htaccess :

RewriteEngine on

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(?:news/)?(.*?)\.html$ /news/subfolder/$1.html [L] 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download