I’m trying to modify my .htaccess file to modify my URL and have tried many methods but cannot achieve exactly what I want. For example I have this URL:
http://mywebsite.com/FOLDER/index.php?id=5
Now I want it to look like:
http://mywebsite.com/FOLDER/5
or
http://mywebsite.com/FOLDER/ID/5
My .htaccess contains the following code:
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^index/([0-9]+)/([0-9a-zA-Z_-]+) index.php?id=$1 [NC]
I cannot figure out what’s wrong. Thanks.
2
Answers
The first argument of
RewriteRule
is what the incoming url without domain and without preceding paths (more on that later) is going to be matched against. This url is, in your case,http://mywebsite.com/FOLDER/5
. Assuming that your.htaccess
file is in your DocumentRoot, the regex will match againstFOLDER/5
.You are currently trying to match
FOLDER/5
with^index/([0-9]+)/([0-9a-zA-Z_-]+)
, which is not going to work. A better regex would be^(.*)/([0-9]+)$
or^(.*)/ID/([0-9]+)$
. You can then rewrite to$1/index.php?id=$2
. I would recommend using the[L]
flag to stop rewriting for this round to avoid common problems with multiple rules matching while you do not expect them to.Besides this, make sure that your
.htaccess
files are being read (e.g. by checking that if you enter garbage, you get a 500 internal server error), that mod_rewrite is enabled, that you are allowed to overrideFileInfo
. You also may need to turnAcceptPathInfo
off.You can use: