服务器配置教案 Help

8-1 Apache服务

HTTP介绍

超文本传输协议(英语:HyperText Transfer Protocol,缩写:HTTP)是一种用于分布式、协作式和超媒体信息系统的应用层协议。HTTP是万维网的数据通信的基础。 设计HTTP最初的目的是为了提供一种发布和接收HTML页面的方法。通过HTTP或者HTTPS协议请求的资源由统一资源标识符(Uniform Resource Identifiers,URI)来标识。 HTTP的发展是由蒂姆·伯纳斯-李于1989年在欧洲核子研究组织(CERN)所发起。HTTP的标准制定由万维网协会(World Wide Web Consortium,W3C)和互联网工程任务组(Internet Engineering Task Force,IETF)进行协调,最终发布了一系列的RFC,其中最著名的是1999年6月公布的 RFC 2616,定义了HTTP协议中现今广泛使用的一个版本——HTTP 1.1。 2014年12月,互联网工程任务组(IETF)的Hypertext Transfer Protocol Bis(httpbis)工作小组将HTTP/2标准提议递交至IESG进行讨论,于2015年2月17日被批准。HTTP/2标准于2015年5月以RFC 7540正式发表,取代HTTP 1.1成为HTTP的实现标准。

8 1 http

主流http服务器软件:

  • Apache HTTP Server。本节内容。擅长动态网站。

  • Nginx。下节内容。擅长静态网站高性能。

  • Windows IIS。略,见教材。图形化界面操作直观简单。

Apache HTTP Server介绍

Apache软件基金会:(Apache Software Foundation,简称为ASF),是一家美国的非营利组织,旨在支持各类开源软件项目。ASF最初由Apache HTTP Server的一群开发者组成,并在1999年3月25日正式成立。 截至2021年,其总成员数大约在1000名。

Apache HTTP Server: (简称Apache),世界流行的http web服务器之一。

准备

网卡: 桥接 。本校区教室和wifi间可以互相访问,意味着你的网站可以被全校访问🎉!

安装

软件名: httpd

(可选)检测是否已安装

yum list installed | grep httpd

(跳过)在线安装

yum install httpd

离线安装

  1. 老师下发离线安装包到学生机桌面。宿主机中复制,虚拟机中图形化文件管理器中粘贴,即下载安装包到/root目录下。

  2. 解压缩解包

tar -zxvf httpd-installer.tar.gz
  1. 安装

rpm -iv --nodeps --force ./httpd-installer/*.rpm

准备网页

默认网站目录在 /var/www/html/

  1. 简单版

    echo "Hello, World!" | sudo tee /var/www/html/index.html

    tee命令用于把前一个命令的输出内容写入文件并返回信息。
    上面命令相当于touch /var/www/html/index.htmlnano /var/www/html/index.html ,编辑内容, cat /var/www/html/index.html

  2. 复杂一点,把老师提供的或网上下载的包含html的网站文件夹放入/var/www/html/下面。宿主机上复制,虚拟机文件管理器/其它位置/计算机/var/www/html/下粘贴。

  3. 文件权限
    (可跳过,但做了更保险)
    后续测试访问网站403错误,http 403响应码是无权限的意思,但这节课的静态网站并不涉及注册登录等需要权限验证的网站。
    可能性有:1)SeLinux导致。2)httpd进程以apache用户执行。出于安全设计的考虑,进程如果由root执行可能被黑客获取服务器目录下所有文件,httpd主配置文件中也有相关定义。
    而网页代码复制到root用户登录的虚拟机时文件创建人是root,所以导致apche用户的进程无权限读取root创建的html文件。
    解决办法是降低html文件权限。
    chown -R apache:apache /var/www/html
    chmod -R 755 /var/www/html

配置介绍

cat /etc/httpd/conf/httpd.conf

本节入门实验不用修改,看看配置项具体负责的功能,里面加了些中文注释。

# # This is the main Apache HTTP server configuration file. It contains the # configuration directives that give the server its instructions. # See <URL:http://httpd.apache.org/docs/2.4/> for detailed information. # In particular, see # <URL:http://httpd.apache.org/docs/2.4/mod/directives.html> # for a discussion of each configuration directive. # # See the httpd.conf(5) man page for more information on this configuration, # and httpd.service(8) on using and configuring the httpd service. # # Do NOT simply read the instructions in here without understanding # what they do. They're here only as hints or reminders. If you are unsure # consult the online docs. You have been warned. # # Configuration and logfile names: If the filenames you specify for many # of the server's control files begin with "/" (or "drive:/" for Win32), the # server will use that explicit path. If the filenames do *not* begin # with "/", the value of ServerRoot is prepended -- so 'log/access_log' # with ServerRoot set to '/www' will be interpreted by the # server as '/www/log/access_log', where as '/log/access_log' will be # interpreted as '/log/access_log'. # # ServerRoot: The top of the directory tree under which the server's # configuration, error, and log files are kept. # # Do not add a slash at the end of the directory path. If you point # ServerRoot at a non-local disk, be sure to specify a local disk on the # Mutex directive, if file-based mutexes are used. If you wish to share the # same ServerRoot for multiple httpd daemons, you will need to change at # least PidFile. # # 服务器根目录,下面有配置和日志 ServerRoot "/etc/httpd" # # Listen: Allows you to bind Apache to specific IP addresses and/or # ports, instead of the default. See also the <VirtualHost> # directive. # # Change this to Listen on specific IP addresses as shown below to # prevent Apache from glomming onto all bound IP addresses. # #Listen 12.34.56.78:80 # 默认监听来自所有客户端的请求即0.0.0.0,在80端口。在浏览器访问时80端口会被自动补充因此可以省略,访问http://127.0.0.1:80与http://127.0.0.1一致。 Listen 80 # # Dynamic Shared Object (DSO) Support # # To be able to use the functionality of a module which was built as a DSO you # have to place corresponding `LoadModule' lines at this location so the # directives contained in it are actually available _before_ they are used. # Statically compiled modules (those listed by `httpd -l') do not need # to be loaded here. # # Example: # LoadModule foo_module modules/mod_foo.so # Include conf.modules.d/*.conf # # If you wish httpd to run as a different user or group, you must run # httpd as root initially and it will switch. # # User/Group: The name (or #number) of the user/group to run httpd as. # It is usually good practice to create a dedicated user and group for # running httpd, as with most system services. # User apache Group apache # 'Main' server configuration # # The directives in this section set up the values used by the 'main' # server, which responds to any requests that aren't handled by a # <VirtualHost> definition. These values also provide defaults for # any <VirtualHost> containers you may define later in the file. # # All of these directives may appear inside <VirtualHost> containers, # in which case these default settings will be overridden for the # virtual host being defined. # # # ServerAdmin: Your address, where problems with the server should be # e-mailed. This address appears on some server-generated pages, such # as error documents. e.g. admin@your-domain.com # ServerAdmin root@localhost # # ServerName gives the name and port that the server uses to identify itself. # This can often be determined automatically, but we recommend you specify # it explicitly to prevent problems during startup. # # If your host doesn't have a registered DNS name, enter its IP address here. # # 在一些web项目配置中,显式地指明域名,后面外链之类的不容易出错,url更准确。 #ServerName www.example.com:80 # # Deny access to the entirety of your server's filesystem. You must # explicitly permit access to web content directories in other # <Directory> blocks below. # # 访问http://127.0.0.1/index.html即访问服务器/var/www/html/index.html,因此恶意程序可能利用此访问服务器某个文件夹下的所有文件列表,因此出于安全考虑默认禁止访问当前web目录外的其他目录、必需访问文件名而不能获取文件夹列表。 <Directory /> AllowOverride none Require all denied </Directory> # # Note that from this point forward you must specifically allow # particular features to be enabled - so if something's not working as # you might expect, make sure that you have specifically enabled it # below. # # # DocumentRoot: The directory out of which you will serve your # documents. By default, all requests are taken from this directory, but # symbolic links and aliases may be used to point to other locations. # # 网站项目的所在的文件夹,平时最经常修改的地方 # ❗️👇如果把一个包含index.html的文件夹mywebsite放入到/var/www/html下,那么下面配置应该修改为/var/www/html/mysite DocumentRoot "/var/www/html" # ❗️ # # Relax access to content within /var/www. # <Directory "/var/www"> AllowOverride None # Allow open access: Require all granted </Directory> # Further relax access to the default document root: <Directory "/var/www/html"> # # Possible values for the Options directive are "None", "All", # or any combination of: # Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews # # Note that "MultiViews" must be named *explicitly* --- "Options All" # doesn't give it to you. # # The Options directive is both complicated and important. Please see # http://httpd.apache.org/docs/2.4/mod/core.html#options # for more information. # Options Indexes FollowSymLinks # # AllowOverride controls what directives may be placed in .htaccess files. # It can be "All", "None", or any combination of the keywords: # Options FileInfo AuthConfig Limit # AllowOverride None # # Controls who can get stuff from this server. # Require all granted </Directory> # # DirectoryIndex: sets the file that Apache will serve if a directory # is requested. # # 如果没有明确指定网站入口,那么会自动找文件夹下有没有index.html。访问http://127.0.0.1等效http:/127.0.0.1/index.html <IfModule dir_module> DirectoryIndex index.html </IfModule> # # The following lines prevent .htaccess and .htpasswd files from being # viewed by Web clients. # <Files ".ht*"> Require all denied </Files> # # ErrorLog: The location of the error log file. # If you do not specify an ErrorLog directive within a <VirtualHost> # container, error messages relating to that virtual host will be # logged here. If you *do* define an error logfile for a <VirtualHost> # container, that host's errors will be logged there and not here. # ErrorLog "logs/error_log" # # LogLevel: Control the number of messages logged to the error_log. # Possible values include: debug, info, notice, warn, error, crit, # alert, emerg. # LogLevel warn <IfModule log_config_module> # # The following directives define some format nicknames for use with # a CustomLog directive (see below). # LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined LogFormat "%h %l %u %t \"%r\" %>s %b" common <IfModule logio_module> # You need to enable mod_logio.c to use %I and %O LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio </IfModule> # # The location and format of the access logfile (Common Logfile Format). # If you do not define any access logfiles within a <VirtualHost> # container, they will be logged here. Contrariwise, if you *do* # define per-<VirtualHost> access logfiles, transactions will be # logged therein and *not* in this file. # #CustomLog "logs/access_log" common # # If you prefer a logfile with access, agent, and referer information # (Combined Logfile Format) you can use the following directive. # CustomLog "logs/access_log" combined </IfModule> <IfModule alias_module> # # Redirect: Allows you to tell clients about documents that used to # exist in your server's namespace, but do not anymore. The client # will make a new request for the document at its new location. # Example: # Redirect permanent /foo http://www.example.com/bar # # Alias: Maps web paths into filesystem paths and is used to # access content that does not live under the DocumentRoot. # Example: # Alias /webpath /full/filesystem/path # # If you include a trailing / on /webpath then the server will # require it to be present in the URL. You will also likely # need to provide a <Directory> section to allow access to # the filesystem path. # # ScriptAlias: This controls which directories contain server scripts. # ScriptAliases are essentially the same as Aliases, except that # documents in the target directory are treated as applications and # run by the server when requested rather than as documents sent to the # client. The same rules about trailing "/" apply to ScriptAlias # directives as to Alias. # ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" </IfModule> # # "/var/www/cgi-bin" should be changed to whatever your ScriptAliased # CGI directory exists, if you have that configured. # <Directory "/var/www/cgi-bin"> AllowOverride None Options None Require all granted </Directory> <IfModule mime_module> # # TypesConfig points to the file containing the list of mappings from # filename extension to MIME-type. # TypesConfig /etc/mime.types # # AddType allows you to add to or override the MIME configuration # file specified in TypesConfig for specific file types. # #AddType application/x-gzip .tgz # # AddEncoding allows you to have certain browsers uncompress # information on the fly. Note: Not all browsers support this. # #AddEncoding x-compress .Z #AddEncoding x-gzip .gz .tgz # # If the AddEncoding directives above are commented-out, then you # probably should define those extensions to indicate media types: # AddType application/x-compress .Z AddType application/x-gzip .gz .tgz # # AddHandler allows you to map certain file extensions to "handlers": # actions unrelated to filetype. These can be either built into the server # or added with the Action directive (see below) # # To use CGI scripts outside of ScriptAliased directories: # (You will also need to add "ExecCGI" to the "Options" directive.) # #AddHandler cgi-script .cgi # For type maps (negotiated resources): #AddHandler type-map var # # Filters allow you to process content before it is sent to the client. # # To parse .shtml files for server-side includes (SSI): # (You will also need to add "Includes" to the "Options" directive.) # AddType text/html .shtml AddOutputFilter INCLUDES .shtml </IfModule> # # Specify a default charset for all content served; this enables # interpretation of all content as UTF-8 by default. To use the # default browser choice (ISO-8859-1), or to allow the META tags # in HTML content to override this choice, comment out this # directive: # AddDefaultCharset UTF-8 <IfModule mime_magic_module> # # The mod_mime_magic module allows the server to use various hints from the # contents of the file itself to determine its type. The MIMEMagicFile # directive tells the module where the hint definitions are located. # MIMEMagicFile conf/magic </IfModule> # # Customizable error responses come in three flavors: # 1) plain text 2) local redirects 3) external redirects # # Some examples: #ErrorDocument 500 "The server made a boo boo." #ErrorDocument 404 /missing.html #ErrorDocument 404 "/cgi-bin/missing_handler.pl" #ErrorDocument 402 http://www.example.com/subscription_info.html # # # EnableMMAP and EnableSendfile: On systems that support it, # memory-mapping or the sendfile syscall may be used to deliver # files. This usually improves server performance, but must # be turned off when serving from networked-mounted # filesystems or if support for these functions is otherwise # broken on your system. # Defaults if commented: EnableMMAP On, EnableSendfile Off # #EnableMMAP off EnableSendfile on # Supplemental configuration # # Load config files in the "/etc/httpd/conf.d" directory, if any. IncludeOptional conf.d/*.conf

启动服务

  1. 启动httpd服务

    systemctl start httpd
  2. 关闭防火墙
    简单做法,关闭防火墙

    systemctl stop firewalld

    (跳过)正规做法,放通http流量,放通80、443端口

    firewall-cmd --permanent --add-port=80/tcp firewall-cmd --permanent --add-port=443/tcp sudo firewall-cmd --reload
  3. 关闭selinux。必需关闭,否则导致403响应。

    setenforce 0

客户端测试

因为没有搭建DNS服务,不访问域名,直接访问服务端IP。

  1. 本地访问。


    服务器上的火狐浏览器,因为服务端和客户端在同一台机器上,浏览器访问IP应该为本地 127.0.0.1


    当访问127.0.0.1,http服务映射到到*/var/www/html/*目录下找,所以要访问其下的index.html,


    最终的完整的url为http://127.0.0.1/index.html


    测试成功说明httpd服务没问题。

    8 1
  2. 局域网访问。


    应该填写服务器IP,完整url形如http://172.31.5.100/index.html ,⚠️替换成你自己的服务器IP。


    测试成功说明httpd服务没问题,服务端防火墙放通,客户端与服务端连通。

  3. 互联网访问。


    暂无实验条件。只要买了云服务器,你的网站就能🌍全世界访问了。

更复杂的网站

  1. 从网上下载现成的静态网站模板,一个文件夹下有index.html/xx.css/xx.js之类的

  2. 把网站文件夹放入虚拟机 /var/www/html

    8 1

  3. 修改配置,修改网站根目录指向。
    (跳过,不需修改。因为本节一台服务器上只有一个网站,把网站index.html及相关文件粘贴到/var/www/html下)

    nano /etc/httpd/conf/httpd.conf

    修改Document Root路径为自己准备的网站文件夹

    ... # 修改前为DocumentRoot "/var/www/html" DocumentRoot "/var/www/html/TeslaByThreeJs" ...
  4. 测试

    1. 本地测试。虚拟机内火狐浏览器访问http://127.0.0.1:80/index.html ,由于浏览器自动补全http协议和端口号80,httpd服务器自动寻找目录下的index.html,
      因此可缩写为只剩IP127.0.0.1

    2. 局域网测试。宿主机或旁边小伙伴的机器,浏览器输入服务器IP测试,
      访问形如"http://172.22.5.100",替换成自己的服务器IP。

      8 1

Last modified: 25 十一月 2024