skip to Main Content

I’m trying to set up a series of .htacces rules that work like this. My .htacces is inside the doc root.

  1. rewrite the uri (internally) to be relative to a subdirectory
  2. if the resource doesn’t exist return a 200 with a specific file.

Here’s what I have so far:

RewriteEngine on

RewriteCond /some/path/%{REQUEST_URI} !-f
RewriteRule ^ /some/path/index.html [L]

RewriteCond %{REQUEST_URI} !^/some/path
RewriteRule (.*) /some/path/$1 [L] 

This causes my Apache server to return errors. I understand this is wrong but I don’t know why. I’ve been researching this for a few hours. Also if there’s a cleaner way I can do this please let me know, ty!

To clarify the second rewrite pair works by itself (when it comes to using the subdirectory), it’s when used in combination with the first pair (using a file by default) that if fails. Also I don’t want to use ErrorDocument because it must return a 200 in the missing file case

2

Answers


  1. Chosen as BEST ANSWER

    This is what I ended up going with. I ended up modifying the post virtual hosts include in Apache, and added something like this:

    <Directory "/home/*/somepath/*"> 
      RewriteEngine on 
    
      RewriteCond %{REQUEST_URI} !/.well-known/
      RewriteRule !/dist/ /dist%{REQUEST_URI} [L]
    
      Redirect 404 /robots.txt
      FallbackResource /dist/index.html 
    </Directory>
    

  2. RewriteCond /some/path/%{REQUEST_URI} !-f
    RewriteRule ^ /some/path/index.html [L]
    

    This condition will always be successful (/some/path/%{REQUEST_URI} will never map to a file since you need to be testing an absolute file-path here, not a URL-path), so the request is always rewritten to /some/path/index.html.

    Try the following instead (in the root .htaccess file):

    RewriteEngine on
    
    # Stop early if already rewritten to path
    RewriteRule ^some/path(/|$) - [L]
    
    # Test if the requested resource exists at "/some/path/..."
    RewriteCond %{DOCUMENT_ROOT}/some/path%{REQUEST_URI} !-f
    RewriteRule ^ some/path/index.html [L]
    
    # Rewrite everything to "/some/path/..."
    RewriteRule (.*) some/path/$1 [L] 
    

    Note that, with the current rules, any files outside of /some/path/ will not be accessible. (Unless perhaps you have additional .htaccess files in those directories that should be accessible?)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search