Home > Software engineering >  Apache error Document automatic re-write rule
Apache error Document automatic re-write rule

Time:09-22

I like to simplify code if possible but I am not to familiar with .htaccess, I had error documents redirect rule hard coded

ErrorDocument 403 http://example.com/error/404

Then I made it

ErrorDocument 403 http://%{HTTP_HOST}/error/404

my question is so that the .htaccess does not have to be manually modified is there a way to tell it if its https or http? because the above example if i use https ill have to hard code https I would like to check automatically.

CodePudding user response:

Don't use an absolute URL in the ErrorDocument directive

ErrorDocument 403 http://example.com/error/404

You shouldn't be using an absolute URL in the ErrorDocument directive to begin with! This will trigger a 302 response (ie. a 302 temporary redirect) to the target URL. So, this won't send a 403 (or 404) response back to the user-agent on the first response.

(This format of the ErrorDocument directive should only be used in very exceptional circumstances since you also lose a lot of information about the URL that triggered the response in the first place.)

To internally serve a custom error document on the same server, this should be a root-relative URL, starting with a slash (no scheme or hostname). For example:

ErrorDocument 403 /error/404

However, /error/404 is unlikely to be a valid end-point. This should represent a valid resource that can be served. eg. /error/404.html.

(And this naturally gets round the issue of having to specifying HTTP vs HTTPS.)


To answer your specific question...

because the above example if i use https ill have to hard code https

(Although, arguably, you should be HTTPS everywhere these days.)

However, to do what you are asking, you could do something like the following using the REQUEST_SCHEME server variable, for example:

ErrorDocument 403 %{REQUEST_SCHEME}://%{HTTP_HOST}/error/404

Or, if the REQUEST_SCHEME server variable is not available then you can construct this from the HTTPS server variable using mod_rewrite and assign this to an environment variable. For example:

RewriteEngine On
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ - [E=PROTO:http%1]

ErrorDocument 403 %{reqenv:PROTO}://%{HTTP_HOST}/error/404

The %1 backreference contains s when HTTPS is on and is empty otherwise. So the PROTO environment variable is set to either http or https.

This does assume that the SSL is managed by the application server and not a front-end proxy (like Cloudflare Flexible SSL etc.).

  • Related