简体   繁体   中英

how to remove the .php extension from url, for a file named same like a folder

I used this code

## remove the php extention
RewriteEngine on 
RewriteCond %{REQUEST_FILENAME} !-d 
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule ^(.*)$ $1.php

This works for some files the eg example.com/contact , but doesn't work when I have a .php file that is also a directory. For example, in the root folder:

science.php 
science - folder

The articles are in categories eg http://example.com/science/themost-blabla.php - this works, the .php extionsion doesn't appear in the URL.

So I want to know if is any possible to hide the .php extension to science.php because when I type example.com/science ... it redirects me to the content of the science folder....

Index of /science directory:

  • afla-care-a-fost-primul-meci-televizat-de-fotbal-din-lume-1937-arsenal.php
  • cazinoul-din-constanta.php cele-7-minuni-ale-lumii.php
  • descoperire-colosala-a-epavei-navei-spaniole-san-jose-ce-avea-la-bord-o-avere-impresionanta.php
  • imagini/ mitologia-greaca.php poenaru.php
  • top-10-cele-mai-importante-inventii-romanesti-din-istorie.php
  • top-5-enigme-ale-lumii.php turnul-eiffel.php

So, can I do something to hide the extension to this page? Or do I need to change the name of the file - to not be the some as the folder?

Try this

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

One of the "problems" is that mod_dir will try to "fix" the URL when accessing a directory by appending a slash to the end of the URL. However, this can be disabled.

# Prevent mod_dir from automatically appending slashes to directories
DirectorySlash Off

# Disable directory listings
# In cases where there is a directory with no similar .php file and no DirectoryIndex
Options -Indexes

# If a PHP file exists for the requested URL then rewrite to this
RewriteEngine On
RewriteCond %{REQUEST_FILENAME}\.php -f 
RewriteRule (.*) $1.php [L]

If required, bare directories (or rather, the DirectoryIndex ) can be accessed by explicitly appending a slash to the URL. eg. example.com/science/ . However, this is presumably unnecessary (and probably best avoided to avoid user confusion) since I assume example.com/science (no trailing slash, ie. science.php ) returns your "science" category content. Without a DirectoryIndex document, example.com/science/ will simply return a 403 Forbidden. Alternatively you could explicitly remove trailing slashes from such URLs with an external redirect.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM