skip to Main Content

setting url rewriting to have nice urls, i have existing urls like that :
/xxx/test.php

but in the background, it is allways going to the same script with a query :
/xxx/index.php?id=test

with the following rewrite :

RewriteRule ^xxx/([0-9a-z-]*).php$ /xxx/index.php?id=$1 [QSA,L]

it’s working fine.

now, there are old urls still like /xxx/index.php?id=$1
and i want to get rid of these old urls, meaning I want all of them to be for the users like /xxx/test.php with a 301 redirect

i did a rewrite for this but then i’m entering a loop despite the L flag

RewriteCond %{QUERY_STRING} ^id=(.*)$ 
RewriteRule ^xxx/index.php$ /xxx/%1.php? [R=301,L] 

? is it possible to handle that and how ?

and other to describe it is allways use the script :
/xxx/index.php?id=$1
but allways have the right url in the browser displayed

2

Answers


  1. Make your RewriteRule not match index.php or remove the QSA flag.

    Say you type test.php well now you will go to index.php?id=test

    Then Rewrite occurs again and you will go to index.php?id=index&id=test

    Then it will occur again because the page is different: index.php?id=index&id=index&id=test etc.

    So add in your regex a negative lookahead: xxx/(?!index)([0-9a-z-]*).php

    Try:

    RewriteRule ^xxx/(?!index)([0-9a-z-]*).php$ /xxx/index.php?id=$1 [QSA,L]
    
    Login or Signup to reply.
  2. Keep your existing

    RewriteRule ^xxx/([0-9a-z-]*).php$ /xxx/index.php?id=$1 [QSA,L]
    

    which appears to work fine.

    Add in these two lines before that which will catch if there is an id= and strip it out of the URL.

    RewriteCond %{QUERY_STRING} ^id=([^&]*)(.*)$
    RewriteRule ^xxx/([0-9a-z-]*).php$ /xxx/index.php?id=%1%2 [L,R=301]
    
    • ^ start of query string
    • ([^&])* any character except &
    • (.*) any following characters

    So if query string is id=test&something=else RewriteRule will append exactly that and nothing else as there is no more QSA flag.

    Try those 3 lines together (htaccess test website), here is the full htaccess file:

    RewriteCond %{QUERY_STRING} ^id=([^&]*)(.*)$
    RewriteRule ^xxx/([0-9a-z-]*).php$ /xxx/index.php?id=%1%2 [L]
    
    RewriteRule ^xxx/([0-9a-z-]*).php$ /xxx/index.php?id=$1 [QSA,L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search