1

Consider the following rules

RewriteRule ^index\.html$ index.php [L]
RewriteRule ^index\.php$ index.html [R=301]

I want .html to use the .php file, but I want the url to have the .html extension always.

The above rule creates a redirection loop. What's the right way to do this?

1 Answer 1

1

You can either check against the actual request, or prevent looping entirely.

  1. Option 1, check against request:

    RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /index\.php
    RewriteRule ^index\.php$ index.html [R=301]
    

    This makes it so if the actual request isn't index.php, the redirect won't happen.

  2. Option 2, prevent rewrite engine from looping entirely. Add this to the top of your htaccess file:

    RewriteCond %{ENV:REDIRECT_STATUS} 200
    RewriteRule ^ - [L]
    

    The downside with this is that you may have rules that actually want to loop.

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

2 Comments

Thanks, mind explaining what `^[A-Z]{3,9}` does in the first solution?
@stevether The %{THE_REQUEST} var is literally the first line of the HTTP request, e.g. GET /index.php HTTP/1.1, and the ^[A-Z]{3,9} matches the GET part, which is the "method" and can be anywhere between 3 to 9 characters long. If you only care about GET/POST, you can alternatively change that to (GET|POST).

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.