Ad

How To Remove The Need Of Txt Extension With A Final Optional Trailing Slash In Url Using Htaccess

How to remove the need of txt extension of txt files and add a final optional trailing slash in url using htaccess regex in php

my code is

   #turn on url rewriting 
RewriteEngine on

#remove the need for .txt extention
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.txt -f
RewriteRule ^(.*)(/?)$ $1.txt

But it throws 500 Server error.What's wrong with the code?

Ad

Answer

Based on your shown samples, could you please try following, please make sure you clear your browser cache before testing your URLs. Fair warning I haven't tested it as of now.

RewriteEngine ON
RewriteBase /
RewriteCond %{DOCUMENT_ROOT}/$1 !-d
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{DOCUMENT_ROOT}/$1\.txt -f
RewriteRule ^(.*)/?$ $1.txt [L]

EDIT: As per OP's comments adding following solution.

RewriteEngine ON
RewriteBase /
RewriteCond %{REQUEST_URI} /$
RewriteRule ^(.*)/$ $1 [R=301,L]

RewriteCond %{DOCUMENT_ROOT}/$1 !-d
RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteCond %{DOCUMENT_ROOT}/$1\.txt -f
RewriteRule ^(.*)/?$ $1.txt [L]
Ad
source: stackoverflow.com
Ad