0

I'm struggling to redirect using the .htaccess.

Specifically I want to redirect based on a parameter. So for example:

mywebsite.com/2345 would redirect to otherwebsite.com/query?=2345

Is this possible using .htaccess? How would I be able to do it? I've never done anything with htaccess before..

Thank you!

2
  • Sure that is possible. But may I ask how you want to process that request you want to rewrite it to? What logic can directly process a request to /query?=2345? Commented Jan 12, 2019 at 20:22
  • And also it would be helpful if you could narrow down what value that parameter can take. 2345 suggests it can only take numbers, is that the case? Commented Jan 12, 2019 at 20:23

1 Answer 1

1

Sure this is possible:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^/?(\d+)/?$ /query?=$1 [END,QSA]

This rule works likewise in the http server's host configuration or in a dynamic configuration file (".htaccess" style file). For this to work the http server's rewriting module has to be enabled, obviously. And if you decide to use a dynamic configuration script that also will have to be supported and enabled.

In case you receive an "internal server error" (http status 500) using above rule then chances are that you operate a very old version of the apache http server. In that case replace the END flag with the L flag, should work too in this case, though it depends on other rewriting rules you have. In any case you will find a definite hint on the unknown END flag in the http servers error log file.

And a general remark: you should always prefer to place such rules in the http servers host configuration instead of using dynamic configuration files (".htaccess"). Those dynamic configuration files add complexity, are often a cause of unexpected behavior, hard to debug and they really slow down the http server. They are only provided as a last option for situations where you do not have access to the real http servers host configuration (read: really cheap service providers) or for applications insisting on writing their own rules (which is an obvious security nightmare).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.