Nginx 在重写不存在的 URL 时尝试下载文件

Nginx 在重写不存在的 URL 时尝试下载文件

所有对不存在文件的请求都应重写为 index.php?name=$1

所有其他请求都应正常处理。

使用此服务器块,服务器正在尝试下载所有不存在的 URL:

server {
    server_name  www.domain.com;
    rewrite ^(.*) http://domain.com$1 permanent;
}

server {
    listen 80;
    server_name  domain.com;
    client_max_body_size 500M;
    index index.php index.html index.htm;

    root   /home/username/public_html;

    location ~ /\.ht {
        deny  all;
    }

    location ~ \.php$ {
        try_files $uri = 404;
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        include fastcgi_params;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        fastcgi_pass 127.0.0.1:9002;
    }

    location ~* ^.+\.(ogg|ogv|svg|svgz|eot|otf|woff|mp4|ttf|rss|atom|jpg|jpeg|gif|png|ico|zip|tgz|gz|rar|bz2|doc|xls|exe|ppt|tar|mid|midi|wav|bmp|rtf)$ {
        access_log off; 
        log_not_found off; 
        expires max;
    }

    location /plg {
    }

    location / {
        if (!-f $request_filename){
            rewrite ^(.*)$ /index.php?name=$1 break;
        }
    }
}

我已经检查过,我的 default_type = text/html 而不是八位字节流,不确定是怎么回事。

答案1

你应该读如果是邪恶的,下面的方法应该可以解决问题。如果您对某些块有疑问,请发表评论,我会解释。

server {
    server_name             www.domain.com;
    return                  301 $scheme://domain.com$request_uri;
}

server {
    listen                  80;
    server_name             domain.com;
    client_max_body_size    500M;
    index                   index.php index.html index.htm;
    root                    /home/username/public_html;

    location / {

        # Hide ALL hidden files
        location ~* /\. {
            deny  all;
        }

        # Directly deliver, good.
        location ~* ^.+\.(ogg|ogv|svgz?|eot|otf|woff|mp4|ttf|rss|atom|jpe?g|gif|png|ico|zip|t?gz|rar|bz2|doc|xls|exe|ppt|tar|midi?|wav|bmp|rtf)$ {
            access_log off; 
            log_not_found off; 
            expires max;
        }

        # Process PHP files, try_files protects us.
        location ~* \.php$ {
            # You only need this if you want to process requests like:
            # /index.php/foo/bar
            # Which is dangerous!
            fastcgi_split_path_info ^(.+\.php)(/.+)$;

            include          fastcgi_params;
            fastcgi_index    index.php;
            fastcgi_param    SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param    SCRIPT_NAME $fastcgi_script_name;
            fastcgi_pass     127.0.0.1:9002;
            try_files        $uri =404;
        }

        try_files $uri @file-missing;
    }

    location @file-missing {
        rewrite ^(.*)$ /index.php?name=$1 last;
    }
}

相关内容