: HTACCESS redirect a URL with query string in it Basically you can visit /stats.php?player=name by simply typing in https://domain.com/@name and it works perfectly. But I also need the old /stats.php?player=name
Basically you can visit /stats.php?player=name by simply typing in domain.com/@name and it works perfectly. But I also need the old /stats.php?player=name links to redirect to domain.com/@name.
How do I do this? Below is my .htaccess file.
<IfModule mod_rewrite.c>
ErrorDocument 404 /404.php
RewriteRule ^@(w+)$ stats.php?player=
Options +FollowSymlinks
Options -MultiViews
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ .php [NC,L]
</ifModule>
More posts by @Annie201
1 Comments
Sorted by latest first Latest Oldest Best
In this case, where you are already rewriting the "pretty" URL to the "ugly/real" URL you can redirect the ugly URL to the pretty URL by checking against THE_REQUEST. This contains the original HTTP request, before any rewriting has occurred. Otherwise you are in danger of creating a rewrite loop when you rewrite back to the ugly URL. For example:
RewriteCond %{THE_REQUEST} ?player=(w+) HTTP
RewriteRule ^stats.php$ /@%1? [R=301,L]
External redirects should generally come before internal rewrites.
Checking for "stats.php" in the RewriteRule pattern, rather that in the RewriteCond directive lessens the load on the server by not processing every single request (the RewriteRule is processed first). %1 refers to the first parenthesised sub pattern in the RewriteCond pattern. And the trailing ? (an empty query string) essentially removes the query string from the rewritten substitution.
I would also append the L flag and make your current RewriteRule root-relative by prefixing with a slash (assuming this file is in the root of your site). Relative URLs can be problematic in .htaccess files:
RewriteRule ^@(w+)$ /stats.php?player= [L]
Also, move the Options and RewriteEngine directives to the top:
ErrorDocument 404 /404.php
Options +FollowSymlinks
Options -MultiViews
RewriteEngine On
RewriteCond %{THE_REQUEST} ?player=(w+) HTTP
RewriteRule ^stats.php$ /@%1? [R=301,L]
RewriteRule ^@(w+)$ /stats.php?player= [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)$ /.php [NC,L]
(I've also snuck a slash in the last RewriteRule substitution as well. If you use relative URLs then you should also specify a RewriteBase directive.)
The check for <IfModule mod_rewrite.c> is also probably unnecessary. Unless you specifically only want to set an ErrorDocument and Options if this module is available?!
Terms of Use Create Support ticket Your support tickets Stock Market News! © vmapp.org2024 All Rights reserved.