How to Remove .php and .html Extensions from URLs in NGINX?

Patricia Arquette
Release: 2024-11-24 03:53:09
Original
306 people have browsed it

How to Remove .php and .html Extensions from URLs in NGINX?

Removing .php and .html Extensions from URLs in NGINX

To resolve the issue of displaying clean URLs without the .php or .html extensions, you can implement the following configuration in your nginx configuration file.

location / {
    try_files $uri $uri.html $uri/ @extensionless-php;
    index index.html index.htm index.php;
}

location ~ \.php$ {
    try_files $uri =404;
}

location @extensionless-php {
    rewrite ^(.*)$ .php last;
}
Copy after login

This configuration achieves the desired result by first checking for the requested URI. If the URI exists, it is displayed as is. If it does not exist, it checks for the URI with the .html extension. Finally, if neither the URI nor the URI with the .html extension exists, it will rewrite the URI to add a .php extension and attempt to display that file.

By adding this configuration, Nginx will:

  1. Check for http://www.mydomain.com/indexhtml as http://www.mydomain.com/indexhtml.html.
  2. Check for http://www.mydomain.com/indexphp as http://www.mydomain.com/indexphp.php.
  3. If neither indexhtml.html nor indexphp.php exists, rewrite indexhtml to indexhtml.php and indexphp to indexphp.php, respectively.

Once you have added this configuration to your file, restart Nginx, and your URLs should display cleanly without the extensions.

The above is the detailed content of How to Remove .php and .html Extensions from URLs in NGINX?. 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