htaccess rewriting wrong

40 Views Asked by At

I need to rewrite the following urls:

https://example.com/@example_user/ (with or without end slash) to https://example.com/main.php?user=example_user

And https://example.com/@example_user/config/ (with or without end slash) to https://example.com/main.php?user=example_user&site=config

I was trying with the follwing script:

RewriteEngine On

RewriteRule ^@([^/]+)/?$ main.php?user=$1 [L,QSA]

RewriteRule ^@([^/]+)/([^/]+)/?$ main.php?user=$1&site=$2 [L,QSA]

But this happens:

  • https://example.com/@example_user <-Works fine
  • https://example.com/@example_user/ <-rewrites wrong https://example.com/@/@example_user/
  • https://example.com/@example_user/config <-Works fine
  • https://example.com/@example_user/config/ <-Rewrites wrong as https://example.com/@%251/%252

I tried everything I can, but I lack of more knowledge.

1

There are 1 best solutions below

0
Ylich On

I understood that the problem was how the script handled the trailing slashes. So I solved the issue in the following way:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.+)/$ /$1 [L,R=301]

RewriteRule ^@([^/]+)/?$ /main.php?user=$1 [L,QSA]

RewriteRule ^@([^/]+)/([^/]+)/?$ /main.php?user=$1&site=$2 [L,QSA]