我在运行 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/防火墙),因为 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 All
under/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 在他的回答中提出的建议,但不幸的是它并没有解决问题。任何其他建议或指导将不胜感激!
ip addr
(orifconfig
) command run as root on the serverReasons below, also see Postscript for other far-fetching possibilities regarding your router and server configuration.
This smells really fishy, it says that local IP address you used for connecting is very, very, wrong.
If said local IP address in question is something closely resembling
127.0.0.1
or::1
, the address itself is likely to be the root cause of your problem. Because that is not a "real" IP address...IPv4 address
127.0.0.1
or abbreviated IPv6 address::1
means this device, and host namelocalhost
is always locally defined as synonym of this address.When you tried to connect to this address from any device other than the server itself, you are instructing it to connect to port 80 of itself (not the port 80 of server machine).
Since your other device did not run HTTP server on itself, the connection attempt will certainly end with TCP
RST
failure, i.e. the "Connection refused" error you got on your browser.For a remedy: you must use a correct LAN IP address when connecting from other machines: certainly not
localhost
, not127.0.0.1
, and not::1
...Run a command
ifconfig
as root on the server, and look for a block that is NOT namedlo
. The IP address will be a field calledinet addr:
.eth
followed by number, e.g.eth0
.wlan
followed by number, e.g.wlan0
.RUNNING
status (which shows that the LAN connection is enabled and usable).Try starting a browser on the server, then enter that IP address you found in step 1 in the address bar, press Enter.
Postscript
If the IP address you used is correct, then there might be other less-obvious reasons that could cause this problem, like:
You home router may be configured with "Virtual LAN" or port isolation— which would isolate each LAN port and each wireless LAN device in its own little network. Each device is confined and cannot connect to each other (and is only allowed to go straight to the Internet).
Your home router might incorporate layer 3 switch functionalities and is configured with access control list (i.e. firewall) to reject any "incoming connection" to any private LAN IP address, no matter of traffic's origin.
Thus, when your device tried to connect to your server, the router (or rather, the switch) intercepted, and replied back with TCP
RST
instead— resulting in "Connection refused" error.There might be something on your server that produces HTTP 301/302 redirect to
http://localhost/
. This could explain why your other device shownlocalhost
in the address bar even when you entered a real LAN IP address.Namely, the first request went all right; but due to some misconfiguration/misperception occurred on the server or server-side scripts, the client got redirected to
http://localhost/
, which is an incorrect address for reasons already lined in the main section of the answer...The end result is "Connection refused" error in the second request, and
http://localhost/
being in the address bar.Don't debug this with browser, since HTTP 301 redirect is cached. Use GNU
wget
or similar tools to issue request from other device, and look at its output carefully. If you see a redirection status came up before the "Connection refused" error— then that is not a network problem, but rather a server problem.If this happen to be the case, you will need find out what caused the server to produce the redirect, and fix it.
If you got this web root from somewhere else, it might contain a configuration which produces a redirection when it found that client accessed it using non-canonical host name. (This is very common, like when you go to www.stackexchange.com, it would produce a HTTP 301 redirect to stackexchange.com)
If your web application perceived its canonical host name to be just
localhost
, then it would inadvertently produce problematic redirection tohttp://localhost/
.In this case, specifically check your
.htaccess
and application's configuration; then disable said redirect.首先,检查 httpd 是否使用
sudo systemctl httpd status
. 在我们不小心添加了重复规则之前,让我们检查一下 iptables 规则iptables -L
为了确保我们接受所有传入的 http,让我们在表中添加一个 ACCEPT
如果这不能解决问题,请务必检查
/etc/apache2/apache2.conf
. 我们应该在 conf 文件的底部有一个基本的安全模型。例如,这是在我的在 ports.conf 中,确保我们正在侦听所有设备上的 80 端口(现在直到我们为您设置好)
Listen *:80
如果这些都没有导致问题,请检查 apache2 是否也在运行
If you use localhost as a host name from other machines, they try to connect to themselves... On the other machines you have to use the actual address of your server. So
ip address show
this will list all your net interfaces and the addresses (inet
lines that look like:inet 192.168.0.44/24 brd 192.168.0.255 scope global dynamic enp0s31f6
). Ignore thelo
interface (which is the one at address 127.0.0.1), and use theenp*
orwlp*
ones. These will likely have address starting with192.168...
inet
line on your Mac/or Android: http://192.168.0.44/Using the address directly has two inconvenients:
On the Mac you can likely fix problem #2 by adding your server name and address in the
/etc/hosts
file (or whatever its equivalent on OSX). This may no be doable on Android.For #1, if you are extremely lucky all your devices support NETBIOS name resolution and you can use their NETBIOS names (usually their host name).
Posting my own answer, just to clarify what the problem was:
I used
curl --verbose [local-IP]
from the terminal of my Mac and it was clear from the output that it was getting to the Apache server, but Wordpress was redirecting tohttp://localhost/
. So, I checked the Wordpress settings and it hadhttp://localhost/
set as the 'site address'. I changed that tohttp://[local-IP]
and it now works fine. Thanks to everyone who made helpful suggestions!(I guess the moral of this story is to use command-line tools for debugging next time ...)
I have encountered the same problem once, i think you are setting up a local web server using virtual machine. If this is what you are doing please check the firewall configuration of your web server.
If you are able to access Apache server from the same machine and getting error while accessing the same from remote machine then kindly Allow apache in firewall in the web-server.
Run the below mentioned command (It worked on CentOS-7)
Let us know whether you are still facing the same issue.
您可以使用远程计算机上的 nmap 来查看端口 80 是否被过滤。