Home > database >  Redirect Query String via .htaccess
Redirect Query String via .htaccess

Time:12-24

I'm trying to redirect the user via the .htaccess file to create friendly URL example:

UI URL: https://example.com/courses/1

htaccess role

RewriteEngine On 
RewriteRule ^courses/([0-9]{1})$ /courses.php?page=$1

Output URL: https://example.com/courses.php?page=1

And everything is working fine, Now I need to add other query params to the URL like this http://smart-courses.com/courses/1?p1=1&p2=2 so, I need htaccess to redirect me to https://example.com/courses.php?page=1&p1=1&p2=2

I tried to create a new role to check if p1 and p2 are exists and rewrite the URL

RewriteRule ^courses/([0-9]{1,5})?lid=([0-9]{1,})&did=([0-9]{1,})$ /courses.php?page=$1&p1=$2&p1=$3

Also, I tried to take any chars after ([0-9]{1,5}) (page number) and put it after ?page=1 but it did not worked

RewriteRule ^courses/([0-9]{1})\?(.*)$ /courses.php?page=$1&$2

CodePudding user response:

The query string is not part of the path section of the URL that the rule pattern is matched against. If you'd have to capture something from the query string you need to use a RewritetCond, that is documented. In this case however you don't even need to capture anything:

RewriteEngine On 
RewriteRule ^/?courses/(\d)$ /courses.php?page=$1 [QSA]

The QSA flag adds a potential query string to the (rewritten) target URL. The rewriting module takes care to use the correct concatenation here (the & character). Again, this behavior is documented: https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html

Take a look yourself: htaccess.madewithlove.com

  • Related