2

I have a page A.

I want to have a page B which is served as a rewrite of page A using .htaccess.

Is it possible to redirect page A to page B from .htaccess or is it going to go into an endless loop?

1 Answer 1

2

Yes, you can certainly do this. However, you do need to be careful of endless redirect/rewrite loops, as you suggest.

You need to use mod_rewrite in .htaccess. Although, exactly how you implement this can depend on your specific scenario and other directives you may already have in your .htaccess file(s).

In order to prevent a redirect loop, you typically want to make sure that the external "redirect" from Page A to page B only happens for direct requests (ie. requests the user has made) and not requests that have been internally rewritten by your own directives in .htaccess.

Commonly this is done by either:

  • Check the requested URL against THE_REQUEST server variable. This contains the first line of the request header and contains the full (encoded) URL-path and query string. For example:

    GET /PageA.html HTTP/1.1
    

    This does not change throughout the request (ie. is not changed when the request is internally rewritten).

  • OR, check the REDIRECT_STATUS environment variable, which is empty on the initial request and contains "200" (as in 200 OK HTTP response status) after the first successful rewrite. This is arguably cleaner than checking THE_REQUEST in most cases.

  • Alternatively, you can use the END flag (Apache 2.4+), instead of L (last) on the internal rewrite to stop all processing, preventing the rewrite engine to start over and retesting the earlier redirect. However, this may not work if you have other rewrites.

For example:

Given that /PageA.html is the underlying filesystem path that serves the page and /PageB is the URL the user sees then, in the following order:

  1. Externally "redirect" any direct requests for /PageA.html to /PageB

  2. Internally "rewrite" any request for /PageB to /PageA.html.

In .htaccess, using mod_rewrite:

RewriteEngine On

# 1. Redirect direct requests for "/PageA.html"
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^PageA\.html$ /PageB [R=302,L]

# 2. Rewrite "/PageB" back to the actual filesystem path
RewriteRule ^PageB$ PageA.html [L]

Generally, the external redirect should always go before the internal rewrite.

1
  • 1
    Thanks for the thorough answer. Very informative.
    – Rojan Gh.
    Feb 5, 2020 at 7:00

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.