remove .php from url with rewrite rule

前端 未结 3 969
梦毁少年i
梦毁少年i 2021-01-24 13:00

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

相关标签:
3条回答
  • 2021-01-24 13:52

    @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;
    }
    
    0 讨论(0)
  • 2021-01-24 14:00

    Something like this should be what you are looking for.

    location ^/(.*)$ {
      rewrite ^(.*)$ /$1.php;
    }
    
    0 讨论(0)
  • 2021-01-24 14:03

    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;
    }
    
    0 讨论(0)
提交回复
热议问题