Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mod_rewrite check if php file exists

I'm trying to write a few mod_rewrite rules. Everything is working fine at the moment. At the moment my generic URLs look like this:

http://website.com/about-us
http://website.com/privacy

At the moment, these 2 links are mod_rewritten to content.php, because about-us and privacy don't exist as .php files, but rather, their content is stored in a database, which content.php retrieves.

I have another url:

http://website.com/contact-us

Which does exist as a .php file, because it contains custom data. How can I check to see if contact-us.php exists. If it does, redirect website.com/contact-us to website.com/contact-us.php, otherwise, redirect to website.com/content.php

Below is my mod_rewrite file as it stands:

RewriteEngine On

# I want the following condition and rule to look to see if the .php file exists,
# and if it does, redirect to the physical page, otherwise, redirect to content.php
RewriteCond %{DOCUMENT_ROOT}/([a-zA-Z0-9\-_]+).php -f
RewriteRule ^([a-zA-Z0-9\-_]+)\.php$ [L]


RewriteRule ^([a-zA-Z0-9\-_]+)$ /content.php [L]
RewriteRule ^(product1|product2|product3)/(designer1|designer2|designer3)$ /search.php?productType=$1&designer=$2 [L]
RewriteRule ^sale/(product1|product2|product3)$ /search.php?sale=1&productType=$1 [L]

If you need any further information, please let me know! I appreciate the replies :)

like image 367
Phil Cross Avatar asked Oct 27 '13 13:10

Phil Cross


1 Answers

Change your .htaccess code to

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-d # not an existing dir
RewriteCond %{REQUEST_FILENAME} !-f # not an existing file
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}\.php -f # and page.php exists

# redirect to the physical page
RewriteRule ^(.*)$ $1.php [L]

# otherwise, redirect to content.php
RewriteRule ^ /content.php [L]

RewriteRule ^sale/(product[123])$ /search.php?sale=1&productType=$1 [QSA,NC,L]
RewriteRule ^(product[123])/(designer[123])$ /search.php?productType=$1&designer=$2 [QSA,NC,L]

I've also simplified the pattern matching for your other RewriteRules. Notice the use of [QSA] to forward any extra query parameters automatically and [NC] to make the match case-insensitive.

like image 67
Ravi K Thapliyal Avatar answered Sep 27 '22 19:09

Ravi K Thapliyal