remove .php from url with rewrite rule

2019-02-28 07:19发布

问题:

I want to rewrite the url in nginx so that the .php extension can be omitted.

This is what I have, but this isn't working for me. Anyone any idea how to do this?

Thanks.

  server {
        listen 80;
        server_name example.com;
        return 301 $scheme://www.example.com$request_uri;       
}

server {
        listen   80;
        root /usr/share/nginx/www;
        index index.php;
        server_name www.example.com;
        error_page 404 http://www.example.com/404.php;
        autoindex off;
        error_log  /usr/share/nginx/www/nginx_error.log  warn;

   location / {
        rewrite ^(.*)$ /$1.php;
    }

    location = / {
        rewrite ^ /index.php;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
    }

}

this is my whole config file.

回答1:

@Makromat I think the 404 issue you are mentioning in the comments is that your / location is resolving to /.php without a file name, so to solve it we might add another location just to handle this special case

location / {
    rewrite ^(.*)$ /$1.php;
}
location = / {
    rewrite ^ /index.php;
}

Try this and tell me if it works

EDIT:

Ok scratch that, I have a better idea, the first case will fail if the original URL already contains the .php extension so it's better to define it as a fall back solution, try this

location / {
    try_files $uri $uri.php $uri/;
}

Try replace this with your current php block

location ~ \.php$ {
    include fastcgi_params;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
}


回答2:

Spent a while trying to get this to work properly. Both php files and other assets working:

location / {

    if (!-e $request_filename){
        rewrite ^(.*)$ /$1.php;
    }
    try_files $uri $uri/ /index.php?$query_string;
}


回答3:

Something like this should be what you are looking for.

location ^/(.*)$ {
  rewrite ^(.*)$ /$1.php;
}


标签: php nginx