Nginx rewrite *.html to *.php

nginxrewrite

I've setup my first Nginx site and the important rewrites are all done. They had to be manual, no rules would possibly have handled it, so I have a raft of rules like this to handle old URLs that might be indexed or bookmarked:

rewrite ^/html/Air_III.html /designers-elements-air permanent;

There is another set of odd files that seem to get traffic, in parts of the site that we haven't gotten to yet so I just copied them over. Most of these were renamed .php from the old .html and are otherwise unchanged, but there are probably some that are still .html.

I'm looking for a rule that will handle the case of a request for any .html file, in any directory, that doesn't actually match a current file by that name and will rewrite to a .php file if it exists.

In "Apache speak" this would be a redirect permanent rather than a rewrite. I'd rather not track all these down and do them by hand!

Best Answer

You'll need an if statement to check the file existance and rewrite appropriately:

location ~ \.html$ {
    if (!-f $request_filename) {
        rewrite ^(.*)\.html$ $1.php permanent;
    }
}