Bugge
Bugge

Reputation: 35

.htaccess open file in folder with same name

My project is beginning to get a bit messy and I'd like to clean it up with the .htaccess file. Right now it's set up to redirect to 'page1.html' or 'page1.php' when I call 'page1'.

RewriteEngine On
RewriteBase /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s([^.]+)\.php [NC]
RewriteRule ^ %1 [R=301,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^(.*?)/?$ $1.php [NC,L]
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^(.*)$ $1.html [NC,L]

But what I want is when I redirect to 'page1' it opens '/page1/page1.html' or '/page1/page1.php'.

I believe it should be achievable with htaccess but I don't have any experience in it so I'm not completely sure.

Thanks in advance :)

Upvotes: 0

Views: 189

Answers (2)

Lawrence Johnson
Lawrence Johnson

Reputation: 4043

Assuming you're trying to do this dynamically, you'd want something like this:

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^([^/]+)/?$ $1/$1.php [NC,L]

Problem is that the server has no way of knowing whether it should serve page1.php or page1.html. You'd be better of routing your traffic into a php bootstrapper that does something like check if a file exists and do one or the other if that's your end game.

If you want to maybe just condense your code but still have a bit of bloat to handle which pages go to html vs php, you could do something like this

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(page1|page2|page5)/?$ $1/$1.php [NC,L]

RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(page3|page4|page6)/?$ $1/$1.html [NC,L]

That would at least allow you to have just two blocks where you can put each page together.

Upvotes: 0

Matin B.
Matin B.

Reputation: 405

I think you can find your answer in this link (maybe the title doesn't seem to be relevant, but surely it is): https://www.digitalocean.com/community/tutorials/how-to-set-up-mod_rewrite-for-apache-on-centos-7

As the link above mentions, you can use the following to do this (this is used for aliasing a file):

RewriteEngine on
RewriteRule ^page1$ /page1/page1.html [NC]

Hope I've understood what you exactly mean.

Upvotes: 2

Related Questions