Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

apache - 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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...