常用基础 - 主机配置

  • 作者:KK

  • 发表日期:2020.03.19


最简单的 http 配置样本

server{
    listen 80;
    server_name 127.0.0.1;
    index index.html;
    root  /home/project;
}

最简单的 https 配置样本

server{
    listen 80;
    listen 443 ssl;

	ssl on;
	ssl_certificate      /home/站点的证书.crt;
	ssl_certificate_key  /home/站点的密钥.key;

	ssl_protocols TLSv1 TLSv1.1 TLSv1.2;# Requires nginx >= 1.13.0 else use TLSv1.2
	ssl_prefer_server_ciphers on; 
	ssl_dhparam /etc/nginx/dhparam.pem; # openssl dhparam -out /etc/nginx/dhparam.pem 4096
	ssl_session_timeout  10m;
	ssl_session_cache shared:SSL:10m;

    server_name 127.0.0.1;
    index index.html;
    root  /home/project;
}

一般情况下至少要有的元素

server{
	listen 80;
	server_name 127.0.0.1;
	index index.html;
	root  /home/project;

	#访问日志和错误日志
	access_log  /home/logs/access.log;
	error_log  /home/logs/error.log;

	#图片、Flash 缓存30天
	location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)${
		expires      30d;
	}

	#JS 和 CSS 缓存 12 小时
	location ~ .*\.(js|css)?${
		expires      12h;
	}
}

PHP 站点样本

server{
	listen 80;
	server_name 127.0.0.1;
	index index.html;
	root  /home/project;

	#访问日志和错误日志
	access_log  /home/logs/access.log;
	error_log  /home/logs/error.log;

	#图片、Flash 缓存30天
	location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)${
		expires      30d;
	}

	#JS 和 CSS 缓存 12 小时
	location ~ .*\.(js|css)?${
		expires      12h;
	}

	location / {
		try_files $uri $uri/ /index.php$is_args$args;
	}

	location ~ [^/]\.php(/|$)
	{
		fastcgi_pass  unix:/run/php/php7.0-fpm.sock; #自己看本机配置具体改一下 php-fpm 的 sock
		fastcgi_index index.php;
		fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
		fastcgi_param  QUERY_STRING       $query_string;
		fastcgi_param  REQUEST_METHOD     $request_method;
		fastcgi_param  CONTENT_TYPE       $content_type;
		fastcgi_param  CONTENT_LENGTH     $content_length;

		fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
		fastcgi_param  REQUEST_URI        $request_uri;
		fastcgi_param  DOCUMENT_URI       $document_uri;
		fastcgi_param  DOCUMENT_ROOT      $document_root;
		fastcgi_param  SERVER_PROTOCOL    $server_protocol;
		fastcgi_param  REQUEST_SCHEME     $scheme;
		fastcgi_param  HTTPS              $https if_not_empty;

		fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
		fastcgi_param  SERVER_SOFTWARE    nginx;

		fastcgi_param  REMOTE_ADDR        $remote_addr;
		fastcgi_param  REMOTE_PORT        $remote_port;
		fastcgi_param  SERVER_ADDR        $server_addr;
		fastcgi_param  SERVER_PORT        $server_port;
		fastcgi_param  SERVER_NAME        $server_name;

		# PHP only, required if PHP was built with --enable-force-cgi-redirect
		fastcgi_param  REDIRECT_STATUS    200;
		fastcgi_param PHP_ADMIN_VALUE "open_basedir=$document_root/../../:/tmp/:/proc/";

		fastcgi_split_path_info ^(.+?\.php)(/.*)$;
		set $path_info $fastcgi_path_info;
		fastcgi_param PATH_INFO       $path_info;
		try_files $fastcgi_script_name =404;
	}
}