Search code examples
apache.htaccessmod-rewriteurl-rewritingfriendly-url

Redirect to Dynamic URL only if that dynamic URL path name file not exist PHP


I want to redirect to dynamic URL only if that path name file not exist in my folders. How I can do this with .htaccess RewriteRule

RewriteRule ^(.*)/(.*)/(.*)/?$ product.php [NC,L]
RewriteRule ^(.*)/(.*)/?$ results.php [NC,L]
ErrorDocument 404   http://example.com/404.php

This rule is working, but with this my Images, CSS & JS files are not loading.

I want to redirect these dynamic URLs like http://example.com/abc/xyz to results.php and http://example.com/abc/xyz/tuv to product.php only if "abc/xyz" and "abc/xyz/tuv" not exist as files in my folder.

How we can do this.

Thanks


Solution

  • With your shown samples, could you please try following. This looks for if folder names mentioned by you are NOT existing in system as an actual directory/folder then rewrite them in backend to product.php(for abc/xyz/tuv) and to results.php(for abc/xyz) file.

    Please make sure to clear your browser cache before testing your URLs.

    RewriteEngine ON
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^abc/xyz/tuv/?$ product.php [NC,L]
    
    RewriteCond %{REQUEST_FILENAME} !-f 
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^abc/xyz/?$ results.php [NC,L]