Home > OS >  How can I redirect a URL which contains query param to an external URL using .htaccess
How can I redirect a URL which contains query param to an external URL using .htaccess

Time:12-05

I have this unknown URL which was accidentally leaked on an email to customers and I am trying to find a way to redirect it to the intended URL.

I am trying to redirect the following link:

https://domain-name.co.uk/?utm_campaign=Christmas Delivery Dates 2022&utm_source=hs_email&utm_medium=email&_hsenc=p2ANqtz-8fHwrp13cEty26peEmPGQQhC8R4zof7Wtn8wJZt1qvEuVdYEewvACSs9f6NsD7r6hUpdFs

To this PDF URL:

https://domain-name.azureedge.net/path-to-file.pdf

Server config:

  • Apache version - 2.4.54
  • cPannel version - 106.0 (build 10)

Anyone got any ideas?

I have tried the following below. However, it doesn't seem to do anything. I believe it's because my URL is a query string.

RedirectMatch 301 ^https://domain-name.co.uk/?utm_campaign=Christmas Delivery Dates 2022&utm_source=hs_email&utm_medium=email&_hsenc=p2ANqtz-8fHwrp13cEty26peEmPGQQhC8R4zof7Wtn8wJZt1qvEuVdYEewvACSs9f6NsD7r6hUpdFs https://domain-name.azureedge.net/path-to-file.pdf

CodePudding user response:

So, after nearly pulling my hair out, I finally solved the problem with help from the Apache docs. Here is my solution:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{QUERY_STRING} Christmas Delivery Dates 2022
RewriteCond ?#%{QUERY_STRING} ([^#] )#([^#] )
RewriteRule ^ https://domain-name.azureedge.net/path-to-file.pdf [L,B,NE]
</IfModule>
  • I am first checking if the query string Christmas Delivery Dates 2022 is in the URL.
  • I then create a backreference match for the question mark, URI and the query string.
  • Then redirect to the intended URL.
  • Related