Networking

無法從本地家庭網路訪問 Apache 網路伺服器

  • January 9, 2020

我在執行 Trisquel 8(基於 Ubuntu)的台式機上執行 Apache Web 伺服器。我想讓我的本地網路上的其他機器/設備可以訪問伺服器,但我不知道如何。

當我嘗試使用 Apache 伺服器的本地 IP 地址從另一台設備連接時,我在瀏覽器中收到錯誤消息,例如:在 Mac 上的 Firefox 中,我收到“無法連接”。Firefox 無法在本地主機上建立與伺服器的連接。’。如果我嘗試在 Android 手機上使用 DuckDuckGo 瀏覽器進行連接,我會收到“網頁不可用”。無法載入位於http://localhost/的網頁,因為:net::ERR_CONNECTION_REFUSED’。

建議使用的答案之一是nmap查看哪些埠是打開的,它返回了以下結果:

$ nmap [LOCAL IP ADDRESS]

Starting Nmap 7.01 ( https://nmap.org ) at 2019-10-12 09:25 EDT
Nmap scan report for [LOCAL IP ADDRESS]
Host is up (0.00013s latency).
Not shown: 998 closed ports
PORT   STATE SERVICE
22/tcp open  ssh
80/tcp open  http

Nmap done: 1 IP address (1 host up) scanned in 0.09 seconds

因此,它表明埠 80 對 http 開放。可能還值得一提的是,我可以從本地網路上的另一台機器 ping 機器,並且正如 nmap 輸出所示,我為 ssh 打開了另一個埠。我已經在這台機器上 ssh 了幾個月,而且效果很好。為此,我剛剛安裝了 ssh-server,它幾乎可以開箱即用。

那麼,這是否意味著 Apache2 設置有問題(而不是 iptables/firewall),因為 ssh 沒有問題?

iptables的內容:

$ sudo iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination         
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http ctstate NEW,ESTABLISHED

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination         

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination         

apache2.conf 的內容:

# This is the main Apache server configuration file.  It contains the
# configuration directives that give the server its instructions.
# See http://httpd.apache.org/docs/2.4/ for detailed information about
# the directives and /usr/share/doc/apache2/README.Debian about Debian specific
# hints.
#
#
# Summary of how the Apache 2 configuration works in Debian:
# The Apache 2 web server configuration in Debian is quite different to
# upstream's suggested way to configure the web server. This is because Debian's
# default Apache2 installation attempts to make adding and removing modules,
# virtual hosts, and extra configuration directives as flexible as possible, in
# order to make automating the changes and administering the server as easy as
# possible.

# It is split into several files forming the configuration hierarchy outlined
# below, all located in the /etc/apache2/ directory:
#
#       /etc/apache2/
#       |-- apache2.conf
#       |       `--  ports.conf
#       |-- mods-enabled
#       |       |-- *.load
#       |       `-- *.conf
#       |-- conf-enabled
#       |       `-- *.conf
#       `-- sites-enabled
#               `-- *.conf
#
#
# * apache2.conf is the main configuration file (this file). It puts the pieces
#   together by including all remaining configuration files when starting up the
#   web server.
#
# * ports.conf is always included from the main configuration file. It is
#   supposed to determine listening ports for incoming connections which can be
#   customized anytime.
#
# * Configuration files in the mods-enabled/, conf-enabled/ and sites-enabled/
#   directories contain particular configuration snippets which manage modules,
#   global configuration fragments, or virtual host configurations,
#   respectively.
#
#   They are activated by symlinking available configuration files from their
#   respective *-available/ counterparts. These should be managed by using our
#   helpers a2enmod/a2dismod, a2ensite/a2dissite and a2enconf/a2disconf. See
#   their respective man pages for detailed information.
#
# * The binary is called apache2. Due to the use of environment variables, in
#   the default configuration, apache2 needs to be started/stopped with
#   /etc/init.d/apache2 or apache2ctl. Calling /usr/bin/apache2 directly will not
#   work with the default configuration.


# Global configuration
#

#
# ServerRoot: The top of the directory tree under which the server's
# configuration, error, and log files are kept.
#
# NOTE!  If you intend to place this on an NFS (or otherwise network)
# mounted filesystem then please read the Mutex documentation (available
# at <URL:http://httpd.apache.org/docs/2.4/mod/core.html#mutex>);
# you will save yourself a lot of trouble.
#
# Do NOT add a slash at the end of the directory path.
#
#ServerRoot "/etc/apache2"

#
# The accept serialization lock file MUST BE STORED ON A LOCAL DISK.
#
Mutex file:${APACHE_LOCK_DIR} default

#
# PidFile: The file in which the server should record its process
# identification number when it starts.
# This needs to be set in /etc/apache2/envvars
#
PidFile ${APACHE_PID_FILE}

#
# Timeout: The number of seconds before receives and sends time out.
#
Timeout 300

#
# KeepAlive: Whether or not to allow persistent connections (more than
# one request per connection). Set to "Off" to deactivate.
#
KeepAlive On

#
# MaxKeepAliveRequests: The maximum number of requests to allow
# during a persistent connection. Set to 0 to allow an unlimited amount.
# We recommend you leave this number high, for maximum performance.
#
MaxKeepAliveRequests 100

#
# KeepAliveTimeout: Number of seconds to wait for the next request from the
# same client on the same connection.
#
KeepAliveTimeout 5


# These need to be set in /etc/apache2/envvars
User ${APACHE_RUN_USER}
Group ${APACHE_RUN_GROUP}

#
# HostnameLookups: Log the names of clients or just their IP addresses
# e.g., www.apache.org (on) or 204.62.129.132 (off).
# The default is off because it'd be overall better for the net if people
# had to knowingly turn this feature on, since enabling it means that
# each client request will result in AT LEAST one lookup request to the
# nameserver.
#
HostnameLookups Off

# 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 ${APACHE_LOG_DIR}/error.log

#
# LogLevel: Control the severity of messages logged to the error_log.
# Available values: trace8, ..., trace1, debug, info, notice, warn,
# error, crit, alert, emerg.
# It is also possible to configure the log level for particular modules, e.g.
# "LogLevel info ssl:warn"
#
LogLevel warn

# Include module configuration:
IncludeOptional mods-enabled/*.load
IncludeOptional mods-enabled/*.conf

# Include list of ports to listen on
Include ports.conf


# Sets the default security model of the Apache2 HTTPD server. It does
# not allow access to the root filesystem outside of /usr/share and /var/www.
# The former is used by web applications packaged in Debian,
# the latter may be used for local directories served by the web server. If
# your system is serving content from a sub-directory in /srv you must allow
# access here, or in any related virtual host.
<Directory />
       Options FollowSymLinks
       AllowOverride None
       Require all denied
</Directory>

<Directory /usr/share>
       AllowOverride None
       Require all granted
</Directory>

<Directory /var/www/>
       Options Indexes FollowSymLinks
       AllowOverride All
#       Require local
#       Require ip 192.168.1
       Require all granted
</Directory>

#<Directory /srv/>
#       Options Indexes FollowSymLinks
#       AllowOverride None
#       Require all granted
#</Directory>




# AccessFileName: The name of the file to look for in each directory
# for additional configuration directives.  See also the AllowOverride
# directive.
#
AccessFileName .htaccess

#
# The following lines prevent .htaccess and .htpasswd files from being
# viewed by Web clients.
#
<FilesMatch "^\.ht">
       Require all denied
</FilesMatch>


#
# The following directives define some format nicknames for use with
# a CustomLog directive.
#
# These deviate from the Common Log Format definitions in that they use %O
# (the actual bytes sent including headers) instead of %b (the size of the
# requested file), because the latter makes it impossible to detect partial
# requests.
#
# Note that the use of %{X-Forwarded-For}i instead of %h is not recommended.
# Use mod_remoteip instead.
#
LogFormat "%v:%p %h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" vhost_combined
LogFormat "%h %l %u %t \"%r\" %>s %O \"%{Referer}i\" \"%{User-Agent}i\"" combined
LogFormat "%h %l %u %t \"%r\" %>s %O" common
LogFormat "%{Referer}i -> %U" referer
LogFormat "%{User-agent}i" agent

# Include of directories ignores editors' and dpkg's backup files,
# see README.Debian for details.

# Include generic snippets of statements
IncludeOptional conf-enabled/*.conf

# Include the virtual host configurations:
IncludeOptional sites-enabled/*.conf

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

我需要AllowOverride Allunder/var/www因為我正在嘗試執行 Wordpress 的實例,並且它需要能夠寫入 Apache 伺服器。

Apache2 肯定正在執行,因為我可以使用本地電腦上的瀏覽器中的“localhost”訪問 Web 內容。此外,systemctl status apache2顯示它正在執行:

~$ systemctl status apache2
● apache2.service - LSB: Apache2 web server
  Loaded: loaded (/etc/init.d/apache2; bad; vendor preset: enabled)
 Drop-In: /lib/systemd/system/apache2.service.d
          └─apache2-systemd.conf
  Active: active (running) since Thu 2019-10-10 20:01:44 EDT; 5min ago
    Docs: man:systemd-sysv-generator(8)
 Process: 1562 ExecStart=/etc/init.d/apache2 start (code=exited, status=0/SUCCESS)
  CGroup: /system.slice/apache2.service
          ├─1621 /usr/sbin/apache2 -k start
          ├─1624 /usr/sbin/apache2 -k start
          ├─1625 /usr/sbin/apache2 -k start
          ├─1626 /usr/sbin/apache2 -k start
          ├─1627 /usr/sbin/apache2 -k start
          ├─1628 /usr/sbin/apache2 -k start
          └─2102 /usr/sbin/apache2 -k start

Oct 10 20:01:42 lee-Desktop systemd[1]: Starting LSB: Apache2 web server...
Oct 10 20:01:42 lee-Desktop apache2[1562]:  * Starting Apache httpd web server apache2
Oct 10 20:01:43 lee-Desktop apache2[1562]: AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to suppress this message
Oct 10 20:01:44 lee-Desktop apache2[1562]:  *
Oct 10 20:01:44 lee-Desktop systemd[1]: Started LSB: Apache2 web server.

正如評論中所建議的,我試過了netstat --inet -a | grep apache2,但它什麼也沒返回。顯然,如果 apache2 正在執行,這是不尋常的,因為它應該在埠 80 上偵聽。我執行netstat -plunt | grep :80並得到以下輸出:

$ sudo netstat -plunt | grep :80
tcp6       0      0 :::80                   :::*                    LISTEN      1557/apache2    

這是否意味著 Apache 正在聽,但沒有聽到任何聲音?

就同​​樣請求的虛擬主機配置而言,其中唯一的文件/etc/apache2/sites-enabled/是 000-default.conf,其內容為:

<VirtualHost *:80>
       # The ServerName directive sets the request scheme, hostname and port that
       # the server uses to identify itself. This is used when creating
       # redirection URLs. In the context of virtual hosts, the ServerName
       # specifies what hostname must appear in the request's Host: header to
       # match this virtual host. For the default virtual host (this file) this
       # value is not decisive as it is used as a last resort host regardless.
       # However, you must set it for any further virtual host explicitly.
       #ServerName www.example.com

       ServerAdmin webmaster@localhost
       DocumentRoot /var/www/html

       # Available loglevels: trace8, ..., trace1, debug, info, notice, warn,
       # error, crit, alert, emerg.
       # It is also possible to configure the loglevel for particular
       # modules, e.g.
       #LogLevel info ssl:warn

       ErrorLog ${APACHE_LOG_DIR}/error.log
       CustomLog ${APACHE_LOG_DIR}/access.log combined

       # For most configuration files from conf-available/, which are
       # enabled or disabled at a global level, it is possible to
       # include a line for only one particular virtual host. For example the
       # following line enables the CGI configuration for this host only
       # after it has been globally disabled with "a2disconf".
       #Include conf-available/serve-cgi-bin.conf
</VirtualHost>

# vim: syntax=apache ts=4 sw=4 sts=4 sr noet

我也嘗試過執行tail -f /var/log/apache2/*.log,但是當我嘗試從遠端機器連接時,日誌中沒有任何內容。

那麼,如何解決阻塞連接的問題?是否有任何日誌可以啟發我了解連接被拒絕的原因以及原因?

我嘗試了 Jacob 在他的回答中提出的建議,但不幸的是它並沒有解決問題。任何其他建議或指導將不勝感激!

當我嘗試從另一台設備連接時,使用Apache 伺服器的本地 IP 地址

  • 請在伺服器上以 root 身份發布ip addr(或)命令的輸出ifconfig
  • 請指出您當時嘗試從其他設備連接的確切本地 IP 地址
  • 請註明您在連接時使用的其他設備的 LAN IP 地址。

下面的原因,另請參閱Postscript以了解有關您的路由器和伺服器配置的其他牽強的可能性


我確實在瀏覽器中輸入了 apache 伺服器的本地 IP,但由於某種原因,在它嘗試連接並給出錯誤後,它顯示http://localhost/在地址欄中

這聞起來很腥,它說您用於連接的本地 IP 地址非常非常錯誤。

  • 另一種解釋:請求成功通過,但導致了無意義的 HTTP 重定向——跳到後記3。

如果所述本地 IP 地址127.0.0.1與或非常相似::1,則地址本身很可能是您的問題的根本原因。因為那不是一個“真實的”IP地址……

  • IPv4 地址127.0.0.1或縮寫的 IPv6 地址::1 表示此設備,主機名localhost始終在本地定義為此地址的同義詞。

    • 當您嘗試從伺服器本身以外的任何設備連接到此地址時,您正在指示它連接到自身的埠 80(而不是伺服器機器的埠 80)。
    • 由於您的其他設備本身沒有執行 HTTP 伺服器,因此連接嘗試肯定會以 TCPRST失敗結束,即您的瀏覽器上出現“連接被拒絕”錯誤。

補救措施:從其他機器連接時必須使用正確的LAN IP 地址:當然不是localhost,不是127.0.0.1,不是::1……

  1. 在伺服器上ifconfig以 root 身份執行命令,並查找未命名的塊。IP 地址將是一個名為 的欄位**。loinet addr:**
  • 如果伺服器通過有線連接到本地網路,則要使用的塊將被命名eth,後跟數字,例如eth0
  • 如果伺服器以無線方式連接到本地網路,則要使用的塊將以wlan數字命名,例如wlan0
  • 您使用的塊還必須包含RUNNING狀態(表明 LAN 連接已啟用且可用)。
  • 有問題的地址應類似於192.168.xx、10.xxx 或範圍從 172.16.xx 到 172.31.xx
  1. 嘗試在伺服器上啟動瀏覽器,然後在地址欄中輸入您在步驟 1 中找到的 IP 地址,然後按Enter
  2. 如果您的網頁正確顯示,請進行下一步。
  3. 另一台設備上,確保它們連接到同一個 LAN(不是蜂窩網際網路)。
  4. 在另一台設備上啟動瀏覽器,然後輸入您在步驟 1 中找到的 IP 地址,按“開始”。
  5. 您的網頁應該正確顯示。

後記

如果您使用的 IP 地址是正確的,那麼可能還有其他不太明顯的原因可能導致此問題,例如:

  1. 您的家庭路由器可能配置了“虛擬 LAN”或埠隔離——這將在其自己的小網路中隔離每個 LAN 埠和每個無線 LAN 設備。每個設備都是受限的,不能相互連接(並且只允許直接上網)。
  • 在這種配置中,理論上有可能在每個虛擬 LAN 中,為每個設備分配相同的 IP 地址。因此,當您在另一台設備中輸入“伺服器的 IP 地址”時,結果“巧合地”與設備自己的 LAN IP 地址相同——指示它連接到不執行 HTTP 伺服器的*自身——導致“*連接被拒絕“ 錯誤。
  • 如果是這種情況,請禁用路由器上的埠隔離和虛擬 LAN 選項。
  1. 您的家用路由器可能包含第 3 層交換機功能,並配置了訪問控制列表(即防火牆),以拒絕任何與任何私有 LAN IP 地址的“傳入連接”,無論流量的來源如何

因此,當您的設備嘗試連接到您的伺服器時,路由器(或者更確切地說,交換機)截獲並改為使用 TCPRST回复 - 導致“連接被拒絕”錯誤。

  • 如果是這種情況,請將路由器的訪問控制列表更改為僅適用於源自 Internet/PPPoE 的流量;或為本地 IP 地址範圍提供適當的例外。
  1. 您的伺服器上可能有一些東西會產生 HTTP 301/302 重定向到http://localhost/. 這可以解釋為什麼即使您輸入了真實的 LAN IP 地址,地址欄中也會顯示您的其他設備。localhost

即,第一個請求順利;但是由於伺服器或伺服器端腳本上發生了一些錯誤配置/誤解,客戶端被重定向到http://localhost/,這是一個不正確的地址,原因已經在答案的主要部分中列出……

最終結果是第二個請求中的“連接被拒絕”錯誤,並且http://localhost/在地址欄中。

不要使用 browser 調試這個,因為 HTTP 301 重定向被記憶體。使用 GNUwget或類似工具從其他設備發出請求,並仔細查看其輸出。如果您在“連接被拒絕”錯誤之前看到重定向狀態出現- 那不是網路問題,而是伺服器問題。

如果發生這種情況,您將需要找出導致伺服器產生重定向的原因,並修復它。

  • 如果您從其他地方獲得此 Web 根目錄,它可能包含一個配置,當它發現客戶端使用非規範主機名訪問它時會產生重定向。(這很常見,比如當你訪問*www.stackexchange.com時,它會產生一個 HTTP 301 重定向到stackexchange.com*)

如果您的 Web 應用程序認為它的規範主機名是公正localhost的,那麼它會無意中產生有問題的重定向到http://localhost/.

在這種情況下,請專門檢查您.htaccess和應用程序的配置;然後禁用所述重定向。

引用自:https://unix.stackexchange.com/questions/545629