rpsep2
rpsep2

Reputation: 3111

merge QUERY_STRING params with a regex matched param in htaccess

I have a .htaccess file that is redirecting URLS like this:

RewriteRule    ^companies/([0-9]{1,20})/(.*)/?$    /php/company-profile.php?id=$1    [NC,L]

Which matches a URL 'companies/12345/company-name-safe' and grabbing the unique id for company-profile.php.

This works great. But I include a list of jobs by that company on the page, which has pagination & order_by functionality.

So I also need to capture any extra URL params and pass to the php file.

E.g for a url: companies/12345/company-name?page=2&order_by=date+DESC

I don't want to have to change my URL structure if possible, I always want page 1 to be a clean URL without '?id=12345' on the end.

How can I do this?

Upvotes: 0

Views: 256

Answers (1)

Justin Iurman
Justin Iurman

Reputation: 19016

You only have to add a QSA flag to your rule

RewriteRule ^companies/([0-9]{1,20})/(.*)/?$ /php/company-profile.php?id=$1 [NC,L,QSA]

This way, the query string will be appended. From your example companies/12345/company-name?page=2&order_by=date+DESC will be rewritten to /php-profile.php?id=12345&page=2&order_by=date+DESC.

The solution above is only valid if query string parameters can have the same names in your rule. Otherwise, you can capture them separately with a RewriteCond on %{QUERY_STRING} and then append them manually in the rule, for instance:

RewriteCond %{QUERY_STRING} ^page=([^&]+)&order_by=([^&]+)$ [NC]
RewriteRule ^companies/([0-9]{1,20})/(.*)/?$ /php/company-profile.php?id=$1&xxx_page=%1&xxx_order_by=%2 [NC,L]  

Note that in this current case, you don't need QSA flag anymore

Upvotes: 3

Related Questions