skip to Main Content

I am facing a problem in redirecting from old url structure to new url structure

This is the old URL: https://example.com/user?username=ganesh

And this is the new URL: https://example.com/user/ganesh

Actually I rewrite the old URL to a new URL successfully with the help of the below htaccess code, so rewriting of URL is working fine.

RewriteRule ^/?user/(.*?)/?$ /user.php?username=$1 [L]

But now I want to redirect all the old structured URLs to a new URL. So, I tried the below code to redirect it but after applying this below code I am unable to access the page with this URL https://example.com/user?username=ganesh and I am able to access the new URL https://example.com/user/ganesh

RewriteCond %{QUERY_STRING} ^username=(.*?)/?$ [NC]
RewriteRule ^/user$ /user/%1? [R=302,L,NC]

Trying to do this since last 2 days but no luck, Any help will be appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    @anubava code works perfectly although my condition was a little different.

    Previously I was trying

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule !.*.php$ %{REQUEST_FILENAME}.php [QSA,L]
    
    Options -MultiViews
    RewriteEngine On
    
    RewriteCond %{THE_REQUEST} s/+user?username=([w-]+)s [NC]
    RewriteRule ^ /user/%1? [R=301,L]
    
    RewriteRule ^/?user/([w-]+)/?$ user.php?username=$1 [L,QSA]
    

    and Finally, after months I changed it like below and it worked perfectly

    Options -MultiViews
    RewriteEngine On
    
    RewriteCond %{THE_REQUEST} s/+user?username=([w-]+)s [NC]
    RewriteRule ^ /user/%1? [R=301,L]
    
    RewriteRule ^/?user/([w-]+)/?$ user.php?username=$1 [L,QSA]
    
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME}.php -f
    RewriteRule !.*.php$ %{REQUEST_FILENAME}.php [QSA,L]
    

    I don't have much experience with .htaccess but I am writing here, I hope it may help someone.


  2. You may use these rules in your site root .htaccess:

    Options -MultiViews
    RewriteEngine On
    
    RewriteCond %{THE_REQUEST} s/+user.php?username=([w-]+)s [NC]
    RewriteRule ^ /user/%1? [R=301,L]
    
    RewriteRule ^/?user/([w-]+)/?$ user.php?username=$1 [L,QSA]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search