![NGINX:静态提供 /images/ 文件夹](https://linux22.com/image/626277/NGINX%EF%BC%9A%E9%9D%99%E6%80%81%E6%8F%90%E4%BE%9B%20%2Fimages%2F%20%E6%96%87%E4%BB%B6%E5%A4%B9.png)
为了做到这一点,我已经尝试了很多方法,比如将一个 php 文件放在 /images/test.php 里面来测试它是否会被下载或执行,结果它总是会被执行。
另外,我有很多 SEO 重写,所以我真的不知道发生了什么。
这是我目前正在尝试的(并且我已经阅读了很多关于它的文档):
服务器配置:
user nginx nginx;
worker_processes 1;
error_log /var/log/nginx/error_log info;
events {
worker_connections 1024;
use epoll;
}
http {
#proxy_cache off;
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main
'$remote_addr - $remote_user [$time_local] '
'"$request" $status $bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$gzip_ratio"';
client_header_timeout 10m;
client_body_timeout 10m;
send_timeout 10m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 4 2k;
request_pool_size 4k;
gzip on;
gzip_min_length 1100;
gzip_buffers 4 8k;
gzip_types text/plain;
output_buffers 1 32k;
postpone_output 1460;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 75 20;
ignore_invalid_headers on;
index index.php;
proxy_buffering on;
proxy_buffer_size 8k;
proxy_buffers 2048 8k;
server {
listen 127.0.0.1;
server_name <<my_domain>>;
access_log /var/log/nginx/access_<<my_domain>> main;
error_log /var/log/nginx/error_<<my_domain>> info;
root <<doc_root>>;
error_page 403 /errors.php?type=403;
error_page 404 /errors.php?type=404;
location ~* /images {
root <<doc_root>>;
#expires 30d;
}
location ~ \.php$ {
#internal;
try_files $uri =404;
expires off;
include /etc/nginx/fastcgi.conf;
fastcgi_pass unix:/var/run/php-fpm.socket;
}
#For virtual folders which are links seo-friendly and language
location ~ (*UTF8)^.*$ {
include "rewrites.conf";
}
}
server {
listen 127.0.0.1:443;
server_name <<my_domain>>;
ssl on;
ssl_certificate /etc/ssl/nginx/.crt;
ssl_certificate_key /etc/ssl/nginx/.key;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;
ssl_ciphers ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA:DHE-RSA-AES256-SHA384:DHE-RSA-AES256-SHA256:RC4-SHA;
ssl_protocols TLSv1.2 TLSv1.1 TLSv1 SSLv3;
ssl_prefer_server_ciphers on;
access_log /var/log/nginx/access_ssl_<<my_domain>> main;
error_log /var/log/nginx/error_ssl_<<my_domain>> info;
root <<doc_root>>;
error_page 403 /errors.php?type=403;
error_page 404 /errors.php?type=404;
<<the_same_locations_than_www_server_before>>
}
}
那么,我可以静态地提供所有内容/images/
而不通过 php 吗?在此测试用例中,应该下载文件/images/test.php
而不是显示phpinfo();
答案1
因为 ~* 匹配但继续搜索其他正则表达式匹配我认为你想要的是:
location ^~ /images/ {
#This should match /images/ and stop checking.
root <<doc_root>>;
#expires 30d;
}
location ~ \.php$ {
#internal;
try_files $uri =404;
expires off;
include /etc/nginx/fastcgi.conf;
fastcgi_pass unix:/var/run/php-fpm.socket;
}
答案2
根据您的位置块,以“.php”结尾的文件将仅通过 PHP 传递。因此,如果您在“/images”目录中有一个实际文件,它应该将其作为静态文件提供,否则将返回 404 错误。如果文件以“.php”结尾并位于“/images”目录中,它将按顺序运行两个位置块。
是否应该采取其他做法?