nginx - 根据主机重写 url
问题描述
我有一个服务于 Symfony 应用程序的 Nginx 服务器。但是这个应用程序可能会收到来自不同主机的请求(目前/etc/hosts
在public
|-src
|-var
|-...
|-public
| |-host1.com
| | |-file1
| | |-file2
| |-host2.com
| | |-file1
| | |-...
URI 可以采用以下形式(请注意没有子目录名称):
https://host1.com/file1
在这种情况下,我希望 Nginx 检查是否public/host1.com/file1
存在。所以我需要设置一种从/file1
to的重写规则/host1.com/file1
。如果文件存在,Nginx 必须提供它。但如果不是(即https://host1.com/file53
),我希望 Nginx 重定向到 Symfony 应用程序,以便这个可以生成丢失的文件,并提供它。
我怎么能用 Nginx 做到这一点?
这是我的尝试。没有评论下方的 3 行,它作为经典服务器工作。
server {
listen 80;
root /var/www/project/public;
location / {
##############################################
# Here is my try, but Nginx crashes with this:
##############################################
if ($host = "host1.com") {
try_files /host1.com$uri /index.php$is_args$args;
}
try_files $uri /index.php$is_args$args;
}
location ~ ^/index\.php(/|$) {
fastcgi_pass myapp:9000;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
}
location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|eof|woff|ttf)$ {
if (-f $request_filename) {
expires 30d;
access_log off;
}
}
location ~ \.php$ {
return 404;
}
rewrite_log on;
error_log /var/log/nginx/project_error.log notice;
access_log /var/log/nginx/project_access.log;
}
解决方案
正如评论中所建议的,使用不同server
的块是解决方案。
我也遇到了以下部分的问题,它阻止了所有图像请求而不记录它,这在我的调试过程中造成了误解:
location ~* \.(jpg|jpeg|gif|css|png|js|ico|html|eof|woff|ttf)$ {
if (-f $request_filename) {
expires 30d;
access_log off;
}
}
推荐阅读
- python - 当我按键时 Pygame 类播放器不动
- python - 索引/仪表板/主页 最佳实践和惯例
- sql - 在 SAS 中为公式 proc sql 使用宏
- webgl - 如何在 openlayers 6 中替换 ol5 map.getRenderer().registerLayerRenderers([myLayer])?
- pandas - 在 Visual Studio 代码命令行中运行时,熊猫不导入?
- airflow - Airflow 2.x 中 DAG 导入错误的日志消息
- groovy - jenkins 中的 ssh 输出仅显示每行 80 个字符
- json - Json解析losgstash
- ssl - 在客户环境中启动客户端和服务器之间的安全交换
- c# - 为什么我的预期和实际结果相同,但测试失败?