How to access my .html
or .php
file without extension?
This is my Folder structure:
C:\Apache24\htdocs\search-html\test
search-html
test
low.html
high.html
new.html
My URL is 127.0.0.1/search-html/test/low.html
But i want to access this URL like 127.0.0.1/search-html/test/low
for running localhost server I use httpd.exe -k
start on command prompt
CodePudding user response:
You can add a .htaccess
file to the document root to rewrite the url.
# Apache Rewrite Rules
<IfModule mod_rewrite.c>
Options FollowSymLinks
RewriteEngine On
RewriteBase /
# Add trailing slash to url
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(\.[a-zA-Z0-9]{1,5}|/|#(.*))$
RewriteRule ^(.*)$ $1/ [R=301,L]
# Remove .php-extension from url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^([^\.] )/$ $1.php
# Remove .html-extension from url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.html -f
RewriteRule ^([^\.] )/$ $1.html
# End of Apache Rewrite Rules
</IfModule>
CodePudding user response:
Use the following in your .htaccess
file. It doesn't really matter where the .htaccess
file is located, providing it is inside the document root and somewhere along the file-path being requested.
If you are requesting URLs of the form http://127.0.0.1/search-html/test/low
then C:\Apache24\htdocs
is your DocumentRoot
(looking at your "folder structure"), as defined in the server config.
RewriteEngine On
# Append ".html" extension if the file exists
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.html -f
RewriteRule !\.\w{2,4}$ %{REQUEST_URI}.html [L]
# Otherwise append ".php" extension if the file exists
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule !\.\w{2,4}$ %{REQUEST_URI}.php [L]
The above rules specifically exclude any URL that already includes what looks-like a file extension. So static resources (images, JS and CSS, etc.) will naturally be excluded.
Alternatively, if you are doing nothing else in .htaccess
and want extensionless URLs then just enable MultiViews. For example:
Options MultiViews
However, this does have some caveats:
- Extensionless URLs are essentially enabled on everything, not just
.html
and.php
files. Including images, JS and CSS etc. - If you later want to do more complex URL rewriting with mod_rewrite then you may need to disable MultiViews and use the mod_rewrite solution instead. MultiViews and mod_rewrite can result in unexpected conflicts.