Thanks sdleihssirhc for your prompt reply. I’m a bit concerned with your regular expression though. I want only the files located under the “somedir” directory to be re-directed and not the files located outside of this directory. For example, when someone visits this link:
Ah, sdleihssirhc, your solution is “loopy.” You always must check the regex to see whether it’ll match the redirection, too, and, if it does, provide an exit strategy (with a better regex OR a RewriteCond).
Can you explain what about the rule puts it at risk for looping? I tried accessing main.php, thinking that maybe the regex doesn’t take parameters into account (so if you accessed main.php, it would try to load main.php?p=main, which would trigger with main.php again), but everything seemed to work fine.
RewriteEngine on
RewriteRule ^/?([a-z]+)\\.php$ main.php?p=$1
RewriteEngine on is perfect.
The RewriteRule’s regex will match (Apache 1 or Apache 2 - good!) a lowercase letter filename with a php file extension. It will then redirect to main.php with a query string.
The problem is that main.php will be matched by {filename}\.php and redirected to main.php with a query string of p=main … until Apache 2 recognizes the loop or Apache 1 gets a restart.
Note 1: Because .htaccess is a per-directory resource, Apache will be looking for (and matching) filename.php then main.php then main.php then …
Note 2: This is very similar to the effect that (.*) has when redirecting to the same directory with the only difference being that you are aware enough to use good regex in your RewriteRule (although, these days, the /? isn’t necessary because there are very few Apache 1.x servers remaining).
You’ve done a good job (with the exception of the loop), though. My solution would be very similar:
RewriteEngine on
# Prevent the loop by requiring that there be no query string, i.e.
# RewriteCond %{QUERY_STRING} ^$
# OR that the file requested is not main.php (very slight preference)
RewriteCond %{REQUEST_URI} !main\\.php$
# I prefer my .htaccess to be in the DocumentRoot so I've got to include the somedir
RewriteRule ^somedir/([a-z]+)\\.php$ somedir/main.php?p+$1 [L]
I hope that answers your question (and provides a useable solution for tmyonline).
For tmyonline, may I offer the tutorial Article located in my signature – it’s helped members here for years.