Home » Php » php – How to differentiate between a url with and without parameters using .htaccess

php – How to differentiate between a url with and without parameters using .htaccess

Posted by: admin February 25, 2020 Leave a comment

Questions:

I don’t even know how I could title this question but here is the problem:

I use seo friendly urls on this project where there are services. Service links look like; .com/services/service-title-6 and they get translated to; .com/services.php?s=service-title-6. On the other hand, pages don’t have the .php extension at the end of their urls like: .com/services or .com/about-us.

The actual problem comes when I’m handling the switch between multiple display languages for this website. I just used a get parameter called lang and I can pass it to any page since I have a php file I call on every page to handle this along with other stuff. On my navigation bar, the language change button links are created dynamically so that the user doesn’t have to leave the current page to change the website’s language. So if you are viewing the about page, the link is: .com/about-us?lang=en to switch to English. This is generated in php like $current_url . "?lang=en".

However, when I’m viewing a page with parameters such as a service, the link gets translated by .htaccess to something like: .com/services.php?s=service-title-6?lang=en. As you can tell, the 2nd question mark will get ignored as a parameter and not be passed. I would need to use an ampersand instead of the question mark. But when I’m just doing this on a regular page, I can’t use ampersand by itself as it will be translated to: .com/about-us.php&lang=en.

Sorry for the long question but any help and ideas to handle this problem would be appreciated. Thanks.

How to&Answers:

I fixed my problem by appending the next query string to my url. I wasn’t aware of the QSA flag of mod_rewrite.

Here is my original rule for the services page:

RewriteRule ^services/(.*?)/?$ services.php?s=$1 [L]

I replaced it with:

RewriteRule ^services/(.*?)/?$ services.php?s=$1&lang=$2 [L,QSA]

I don’t know if it’s 100% reliable but it seems to work perfectly for what I need, even after doing a few tests.

(Thanks to Joseph Sible-Reinstate Monica for directing me to a helpful question.)