skip to Main Content

This is .htaccess file I currently have:

Options -Indexes
AddDefaultCharset utf-8
ErrorDocument 403 /error.html
ErrorDocument 404 /error.html
<Files ".ht*">
    Require all granted
</Files>
RewriteEngine on
RewriteRule ^error.html$ / [R=301]
RewriteRule ^.ht / [L,R=301,NC]

I need to add a specific rule to map a non-existent file to a script, like so:

RewriteRule /folder/file.txt /folder/file.php [L]

How do I add this rule to the .htaccess?

I tried:

Options -Indexes
AddDefaultCharset utf-8
ErrorDocument 403 /error.html
ErrorDocument 404 /error.html
<Files ".ht*">
    Require all granted
</Files>
RewriteEngine on

RewriteCond "%{REDIRECT_URL}" "/folder/file.txt"
RewriteRule ^error.html$ /folder/file.php [L]

RewriteRule ^error.html$ / [R=301]
RewriteRule ^.ht / [L,R=301,NC]

but it doesn’t work.

Thank you!

2

Answers


  1. To map a non-existent file /folder/file.txt to /folder/file.php you can use the following :

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^folder/file.txt$ /folder/file.php [L]
    

    Here is a generic rule that rewrites all .txt files to .php

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.+?).tx$ /$1.php [L]
    
    Login or Signup to reply.
  2. With your shown samples, please try following htaccess Rules file. Make sure to keep your htaccess file in root directory.

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

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{DOCUMENT_ROOT}/folder/file.php -f [NC]
    RewriteRule ^folder/file.txt$ /folder/file.php [NC,L]
    


    OR in case you want to match any .txt in uri not only file.txt then try following Rules, make sure to try either above rules set OR following one at a time only.

    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{DOCUMENT_ROOT}/folder/$1.php -f [NC]
    RewriteRule ^folder/([^.]*).txt$ /folder/$1.php [NC,L]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search