Home > other >  Multiple RewriteConds / RewriteRules depending on file existence of single rule targets
Multiple RewriteConds / RewriteRules depending on file existence of single rule targets

Time:04-29

I am currently working on a static website where I need the last URI-element being passed along as query-parameter on some pages.

All my static html pages are inside the /pages/**/* directory, where the paths directly correlate to the desired paths on the final website. Meaning /products/kitchen would require /pages/products/kitchen.html to be shown. If, in this example, the file /pages/products/kitchen.html would not exist, I would like to try /pages/products.html instead and pass on kitchen as query argument named id (?id=kitchen). There are static assets in an /assets directory, so files that exist should not be rewritten to the /pages directory at all. If there is no requested path, I would like to redirect to the default home-page. The probe.json rule is for liveliness-checks in a kubernetes cluster, I just kept it in there because I can not be 100% sure that it is not the culprit.

I tried to chain multiple RewriteConds and RewriteRules together in an if > else if > else if > else way, but that seems to be failing at some point. Unfortunately, those errors are very tricky to debug because there is no indication of what is happening besides the browsers 404-error. Currently, only the rule for existing files and for the default page is working correctly. Any help on what I am doing wrong would be appreciated!

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .? - [L]

<files probe.json>
    order allow,deny
    allow from all
</files>

RewriteCond pages/$1.html -f
RewriteRule ^(.*)$ pages/$1.html [NC,L]

RewriteCond pages/$1.html -f
RewriteRule ^(.*(?=[/]))/(.*)$ pages/$1.html?id=$2 [NC,L]

RewriteRule ^$ pages/home.html [L]

CodePudding user response:

I found the solution for this problem.

  1. I had to use absolute paths.

  2. I had to add %{DOCUMENT_ROOT} infront of the condition.

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} -f
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule .? - [L]

<files probe.json>
    order allow,deny
    allow from all
</files>

RewriteCond %{DOCUMENT_ROOT}/pages/$1.html -f
RewriteRule ^(.*)$ /pages/$1.html [NC,L]

RewriteCond %{DOCUMENT_ROOT}/pages/$1.html -f
RewriteRule ^(.*(?=[/]))/(.*)$ /pages/$1.html?id=$2 [NC,L]

RewriteRule ^$ /pages/home.html [L]
  • Related