Home >Backend Development >PHP Tutorial >How to Remove .php Extension From URLs Using .htaccess (Updated Solution)?

How to Remove .php Extension From URLs Using .htaccess (Updated Solution)?

Linda Hamilton
Linda HamiltonOriginal
2024-11-12 14:33:01349browse

How to Remove .php Extension From URLs Using .htaccess (Updated Solution)?

How to Remove .php Extension Using .htaccess (Updated Solution)

Your previous attempts to hide the .php extension using .htaccess were unsuccessful. To address this issue, consider the following improved solution:

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]

This code snippet includes the following rules:

  • If the request is not for a directory, it removes the trailing slash from the URL.
  • If the request is external and has a .php extension, it redirects to the extensionless URL.
  • Finally, it resolves the .php file for extensionless PHP URLs.

Ensure that your .htaccess file is placed in the root directory. After making these changes, your .php files should be accessible without the extension.

The above is the detailed content of How to Remove .php Extension From URLs Using .htaccess (Updated Solution)?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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