No php extension and pretty url nginx config alternative

雨燕双飞 提交于 2021-02-08 11:37:54

问题


I just migrated my code from apache to nginx server.

What would be the alternative nginx config to my apache .htaccess.

What i use are rules for removing .php extension and pretty url rewrite.

RewriteEngine On

#remove .php
RewriteCond %{REQUEST_FILENAME}.php -f
RewriteRule ^([^\.]+)$ $1.php [NC,L]

#for pretty url
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ index.php?url=$1 [NC,L]

回答1:


Try this

map $uri $pretty_url {
    ~/(.*)$    $1;
}

server {

    ...

    location / {
        index index.php; # replace this to 'index index.php index.html index.htm;' if needed
        try_files $uri $uri/ @extensionless-php;
    }

    location ~ \.php$ {
        # default PHP-FPM handler here
        ...
    }

    location @extensionless-php {
        if ( -f $document_root$uri.php ) {
            rewrite ^ $uri.php last;
        }
        rewrite ^ /index.php?url=$pretty_url last;
    }

}



回答2:


Easy fix by changing one line. There's no need for extra blocks. You just need to change this one line in the /etc/nginx/nginx.conf or /etc/nginx/sites-available/your-site.com.

Change the location / directive try files to:

location / {
       try_files $uri $uri/ $uri.html $uri.php$is_args$query_string;
}

Hope this works for you too :)



来源:https://stackoverflow.com/questions/64238586/no-php-extension-and-pretty-url-nginx-config-alternative

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!