Home > Backend Development > PHP Tutorial > How Can I Use .htaccess to Remove the .php Extension From My Website URLs?

How Can I Use .htaccess to Remove the .php Extension From My Website URLs?

Patricia Arquette
Release: 2024-11-06 17:19:02
Original
350 people have browsed it

How Can I Use .htaccess to Remove the .php Extension From My Website URLs?

How to Conceal .php Extension Using .htaccess

Removing the .php file extension can be a useful technique for maintaining website cleanliness and enhancing user experience. However, achieving this can be challenging.

Detailed Explanation:

Your code attempts to rewrite URLs within the "folder" directory, redirecting them to their .php counterparts. However, your code seems to be incorrect.

Solution:

The following code resolves this issue effectively:

RewriteEngine On

# Unless directory, remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/$ http://example.com/folder/ [R=301,L]

# Redirect external .php requests to extensionless URL
RewriteCond %{THE_REQUEST} ^(.+)\.php([#?][^\ ]*)?\ HTTP/
RewriteRule ^(.+)\.php$ http://example.com/folder/ [R=301,L]

# Resolve .php file for extensionless PHP URLs
RewriteRule ^([^/.]+)$ .php [L]
Copy after login
  1. The first rule strips trailing slashes from non-directory URLs.
  2. The second rule redirects requests containing a .php extension to their extensionless counterparts with a 301 (Moved Permanently) status code.
  3. The third rule serves the corresponding .php file for URLs that lack an extension.

For further guidance, refer to the referenced question's solution: https://stackoverflow.com/questions/14425845/remove-php-extension-with-htaccess.

The above is the detailed content of How Can I Use .htaccess to Remove the .php Extension From My Website URLs?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template