Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

htaccess rewrite if redirected file exists

The problem: Some html pages of php equivalents (apple.html, apple.php; orange.html, orange.php), but not all do (grapes.html).

The goal: If the php version exists, rewrite, otherwise keep it the html version.

I have:

Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)\.html$ /$1.php [R]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)\.php$ /$1.html [R]

Interesting issues:

If I don't put / in front of $1.php then I end up with: site.com/document/root/path (ie: site.com/home/user/www/file.php)

When calling the second RewriteRule, I get http://site.com/http:/site.com/page.html and it tells me there were too many redirects. Notice how there is only one / in the second http.

I've made some progress, I added RewriteBase / and removed the / before the $1, but I still get the too many redirects error (the web page at site.com/page.html has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer).

It seems like if I just rewrite html -> php -> html I get the same error. So it looks like the logic is working, but that sort of logic isn't allowed. I can't think of any other way I could see if a "php version" of a file exists? The only way I can think of is do something similar to:

RewriteCond ^(.*)\.html$ $1.php -f
RewriteRule ^(.*)\.html$ $1.php [R]

Unfortunately that doesn't quite work (I'm guessing because it has three segments on the condition line). I'm trying to get the filename without the extension, then say if filename.php is a file, rewrite page.html to page.php

like image 221
user677285 Avatar asked Mar 25 '11 19:03

user677285


People also ask

How long does it take for htaccess to change effect?

htaccess files follow the same syntax as the main configuration files. Since . htaccess files are read on every request, changes made in these files take immediate effect.

What is rewrite base in htaccess?

mod_rewrite. The RewriteBase directive specifies the URL prefix to be used for per-directory (htaccess) RewriteRule directives that substitute a relative path.


1 Answers

you should be able to achieve that by using two conditions:

RewriteCond %{REQUEST_FILENAME} (.*)\.html$
RewriteCond %1\.php -f
RewriteRule ^(.*)\.html$ $1.php [R,L]

The first condition checks if the filename ended with .html and the second uses the back reference %1 from the first condition to check if .php version exists.

Hope it helps. :)

like image 75
szemian Avatar answered Oct 03 '22 09:10

szemian