skip to Main Content

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


  1. 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 against FOLDER/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 override FileInfo. You also may need to turn AcceptPathInfo off.

    Login or Signup to reply.
  2. You can use:

    RewriteEngine on
    
    # external redirect from actual URL to pretty one
    RewriteCond %{THE_REQUEST} s/+FOLDER/index.php?id=(d+) [NC]
    RewriteRule ^ /FOLDER/%1? [R=301,L,NE]
    
    # internal forward from pretty URL to actual one
    RewriteRule ^FOLDER/(d+)/?$ FOLDER/index.php?id=$1 [L,QSA,NC]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search