Search code examples
.htaccessmod-rewriteurl-rewriting

htaccess: rewrite URL to a file only if that file exists, but with regex captured groups


I have a CMS that I've built myself in PHP (Codeigniter framework). I was thinking why every time PHP has to process all code just that to respond with a page. So instead I will create the complete HTML pages and serve them when a user asks for them.

That is why I need to rewrite an URL to a specific file only if that file exists. For this, I need to use regex captured groups because I want to build this for all files in that folder and subfolders.

For example, I want to put a bunch of HTML pages on %{DOCUMENT_ROOT}/out and want to access them directly with rewrite rules.

For example, if the URL is like this:

htaaatps://www.dsaoidashd.com/services/development-of-desktop-applications

I want to look at the following location:

%{DOCUMENT_ROOT}/out/services

for

development-of-desktop-applications.html 

and if it exists, I want to return it to the client browser without continuing.

And of course, if I have yet more levels like this:

htaaatps://www.dsaoidashd.com/services/development/of-desktop-applications

then I need to check this location:

%{DOCUMENT_ROOT}/out/services/development

for

of-desktop-applications.html 

file and return it to the calling browser.

I tried

I know that I have to use RewriteCond to check if the file exists but how to pass it to the RewriteCond regex captured groups so I can check them based on the URL provided?

RewriteEngine on

RewriteCond %{DOCUMENT_ROOT}/out/$1.html -f
RewriteRule ^.*$ /$1.html [L]

Solution

  • Your RewriteCond is almost correct but you have to capture $1 in a group in RewriteRule and also your target needs to be out/$1.html.

    You can use this rewrite rule in your site root .htaccess:

    RewriteEngine On
    
    # To internally forward /dir/file to /out/dir/file.html
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{DOCUMENT_ROOT}/out/$1.html -f
    RewriteRule ^(.+?)/?$ out/$1.html [L]