htaccess rewrite if redirected file exists

后端 未结 3 947
情书的邮戳
情书的邮戳 2020-12-16 03:50

The problem: Some html pages of php equivalents (apple.html, apple.php; orange.html, orange.php), but not all do (grapes.html).

The goal: If the php version exists,

3条回答
  •  無奈伤痛
    2020-12-16 04:14

    I also wanted to Rewrite all .html request to .php files, but only if the .php file exist. But my variation was that this should only happen if the actual .html file does not exist.

    So only calls to .html files that does not exist is Rewritten to .php file, if they do exists by these rules: (I also have tested this on a XAMP local server and also a Apache online server with success!)

    # Rewrite rules to .html file to .php if the .php version
    # does actually exist.
    
    RewriteCond %{REQUEST_FILENAME} (.*)\.html [NC]
    RewriteCond %{REQUEST_FILENAME} !-f [NC]
    RewriteCond %1\.php -f [NC]
    RewriteRule ^(.*).html$ $1.php [NC]
    
    1. It first check if the requested file is a .html file (we don't want .jpg, .css, .pdf, etc. to be rewritten).
    2. The it checks if that .html file does not exist. (we don't want to rewrite to .php if it actually does exist.)
    3. Then it checks if a .php version does exist (we don't want to rewrite to a non existing .php file).
    4. Then it rewrites the .html to .php

提交回复
热议问题