I am very new to these issues, please help.
I have two questions regarding to mod_rewrite (apache 2.2).
1) What I want to do is to for example, rewrite /login to login.php. This can be done by
RewriteRule ^/?login/?$ /login.php [L]
However, what I wanted to do too is to disable users to access /login.php directly.
If I just write,
RewriteRule ^/?.*\.php$ /file_not_exist.html [L]
This doesn’t work and even /login will be rewritten to /file_not_exist.html.
Is there any way to do that? I notice that in Apache 2.5 documents, there is an [END] flag but I can’t use it yet in Apache 2.2.
2) I want to replace all ajax request to /ajax/action, the following will do,
RewriteRule ^/?ajax/([a-zA-Z]+)/?$ /ajax/$1.php [L]
However, when I try to access /ajax/xyz where xyz.php doesn’t exist, the browser will show that “/ajax/xyz.php” doesn’t exist, which will make ppl know that /ajax/action is implemented by /ajax/action.php.
How to disable such /ajax/xyz.php doesn’t exist message? The only way I can think of now is to enumerate all files in ajax direction and do the following,
RewriteRule ^/?ajax/(action1|action2|action3)/?$ /ajax/$1.php [L]
Then when user access /ajax/xyz, it will just say /ajax/xyz doesn’t exist but not /ajax/xyz.php. But this is very troublesome. Is there any better way to do that?
Thank you very much!
1) If you want to restrict requests for /login.php, you need to use a RewriteCond to check the actual request. Otherwise you’re going to go into a loop.
You could also redirect them to
/loginif you want and let the first rule take care of it:2) You can check if an actual file exists before you rewrite the php, again by using RewriteCond and checking using “-f”
So first we check to make sure the request starts with “/ajax/” and we select the next part “(.+)”. In the next RewriteCond, we use the %1 backreference to access the previous match. So if the request was for “/ajax/blahblah/”, the next RewriteCond would check for “/doc_root/ajax/blahblah.php”. The !-f means “if the file doesn’t exist”. Thus, in this example, if “/doc_root/ajax/blahblah.php” doesn’t exist, then we rewrite the request to “/ajax/no_action.php”. You’d have to replace that with something that you want to handle all of the “bad” requests. Maybe point it to a blank script that simple does nothing so nobody would know the wiser. You can then make a rewrite to change /ajax/(.+)/ to /ajax/$1.php: