简体   繁体   中英

Redirect Query String via .htaccess

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

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 ReuestCond , 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM