安装Nginx

Nginx是一款开源高性能的Web代理服务器,在Ubuntu上使用以下命令安装

#安装nginx
apt install nginx
#启动nginx
service nginx start
#查看运行状态
service nginx status

配置Nginx

不同的Linux发行版本默认的安装位置可能不相同,Ubuntu默认的安装位置为/etc/nginx,安装目录下的文件结构如下

蓝色高亮字体的为文件夹,白色的为文件,也可以使用ll命令查看,nginx.conf文件是默认的配置文件,其部分默认配置如下:

...
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

这部分是虚拟主机配置,也是我们搭建web服务器的核心配置项,两条Include配置声明了要调用的配置文件路径,*是通配符,分别看下两个路径下文件结构

可以看到/etc/nginx/conf.d路径下没有任何文件,因为这是我们创建web服务配置文件大的路径;/etc/nginx/sites-enabled/下有一个default文件,是默认的web服务配置模板,其配置内容如下

# Default server configuration
#
server {
	listen 80 default_server;
	listen [::]:80 default_server;

	# SSL configuration
	#
	# listen 443 ssl default_server;
	# listen [::]:443 ssl default_server;
	#
	# Note: You should disable gzip for SSL traffic.
	# See: https://bugs.debian.org/773332
	#
	# Read up on ssl_ciphers to ensure a secure configuration.
	# See: https://bugs.debian.org/765782
	#
	# Self signed certs generated by the ssl-cert package
	# Don't use them in a production server!
	#
	# include snippets/snakeoil.conf;

	root /var/www/html;

	# Add index.php to the list if you are using PHP
	index index.html index.htm index.nginx-debian.html;

	server_name _;

	location / {
		# First attempt to serve request as file, then
		# as directory, then fall back to displaying a 404.
		try_files $uri $uri/ =404;
	}

	# pass PHP scripts to FastCGI server
	#
	#location ~ \.php$ {
	#	include snippets/fastcgi-php.conf;
	#
	#	# With php-fpm (or other unix sockets):
	#	fastcgi_pass unix:/run/php/php7.4-fpm.sock;
	#	# With php-cgi (or other tcp sockets):
	#	fastcgi_pass 127.0.0.1:9000;
	#}

	# deny access to .htaccess files, if Apache's document root
	# concurs with nginx's one
	#
	#location ~ /\.ht {
	#	deny all;
	#}
}


# Virtual Host configuration for example.com
#
# You can move that to a different file under sites-available/ and symlink that
# to sites-enabled/ to enable it.
#
#server {
#	listen 80;
#	listen [::]:80;
#
#	server_name example.com;
#
#	root /var/www/example.com;
#	index index.html;
#
#	location / {
#		try_files $uri $uri/ =404;
#	}
#}

用一个server{}代码块来配置一个web服务,默认的配置模板开通了一个80端口的web服务,打开浏览器查看一下

下面我们自定义一个配置,先将默认的配置注释掉

 ##
        # Virtual Host Configs
        ##

        include /etc/nginx/conf.d/*.conf;
        #include /etc/nginx/sites-enabled/*;

/etc/nginx/conf.d/路径下创建一个default.conf文件,静态网站配置如下内容

server{
	    #监听端口
        listen 80;
        listen [::]:80;
        #服务地址
        server_name localhost;
        #网站根目录
        root /home/coco/;
        #首页文件
        index index.html;
        #访问路径
        location / {
}
}

该配置文件,监听80端口,打开浏览器访问本地80端口

image-20221117094303562

🍕踩坑:配置nginx时需要修改配置文件nginx.conf将启动用户配置为root,默认启动与用户会由于权限原因导致浏览器访问页面报403错误

#配置启动用户位root
user root;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

更多配置此处不展开赘述。