如何在nginx中制作干净的网址?

时间:2016-03-04 02:38:13

标签: php nginx

我试图将nginx(Ubuntu 14.04)的网址清理干净,而不是example.com/profile.php,例如example.com/profile或example.com/about.html。 COM /约

我已经在stackoverflow上尝试了几乎所有其他的但是它们不起作用,包括使网站有500个内部服务器错误,让我下载PHP文件

当前配置

server {
listen 443 ssl;

root /usr/share/nginx/html;
index index.php index.html index.htm;
include /etc/nginx/mime.types;

server_name mydomain.com;

ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;

ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
ssl_ciphers 'EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH';

location / {
    try_files $uri.html $uri $uri/ =404;
}

location ~ \.php$ {
    try_files $uri =404;
    fastcgi_pass unix:/var/run/php5-fpm.sock;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    include fastcgi_params;
}

}

server {
listen 80;
server_name mydomain.com;
return 301 https://$host$request_uri;
}
server {
listen 443;
server_name api.mydomain.com;
 location / {
            proxy_pass https://mydomain:1337;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_connect_timeout 150;
            proxy_send_timeout 100;
            proxy_read_timeout 100;
            proxy_buffers 4 32k;
            client_max_body_size 8m;
            client_body_buffer_size 128k;
    }
}
server {
listen 1337 ssl;
server_name api.mydomain.com;

root /usr/share/nginx/api;
ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem;
}

1 个答案:

答案 0 :(得分:0)

使用try_files [1]指令。

location / {
    try_files $uri.php $uri.html =404;
}

在此示例中,如果浏览器正在请求/folder/file,则在放弃并抛出404错误之前,它会首先尝试查找file.php然后file.html

如果这不起作用,您可以改为使用if语句:

location / {
    if (-f $request_filename.php) {
        rewrite ^ $uri.php;
        break;
    }
    if (-f $request_filename.html) {
        rewrite ^ $uri.html;
        break;
    }
}
  1. http://nginx.org/en/docs/http/ngx_http_core_module.html#try_files