Tomcat 不支持 htaccess 文件,如何为网站目录设置密码

本贴最后更新于 2598 天前,其中的信息可能已经时移世改
虽然Tomcat也是Apache旗下的,但是并不支持Apache的.htaccess文件。所以Apache下简单的设置.htaccess文件来限制目录访问的方式并不能用。

想要为 Tomcat 网站设置访问密码,需要修改 Tomcat 及网站的配置文件。
具体修改方法:

1. 设置 Tomcat 授权域为 MemoryRealm

打开 Tomcat 配置文件 <TOMCAT_HOME>/conf/server.xml,确保以下代码没有被注释掉

<Realm className="org.apache.catalina.realm.MemoryRealm" />

如果文件中没有这行代码,查找 <Realm,找到后在它同级下一行加入以上代码。
例如,源文件中有

      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>

加入代码变为

      <Realm className="org.apache.catalina.realm.LockOutRealm">
        <!-- This Realm uses the UserDatabase configured in the global JNDI
             resources under the key "UserDatabase".  Any edits
             that are performed against this UserDatabase are immediately
             available for use by the Realm.  -->
        <Realm className="org.apache.catalina.realm.UserDatabaseRealm"
               resourceName="UserDatabase"/>
      </Realm>
	  <Realm className="org.apache.catalina.realm.MemoryRealm" />

2. 配置网站目录约束权限

打开网站中的 WEB-INF/web.xml 文件,例如 <TOMCAT_HOME>/webapps/testwww/WEB-INF/web.xml,将以下内容加入 <web-app> 节点内

<!-- 定义网站资源约束权限 -->
<security-constraint>
	<web-resource-collection>
		<web-resource-name>testwww Application</web-resource-name>
		<url-pattern>/*</url-pattern>
	</web-resource-collection>
	<auth-constraint>
		<role-name>thetestuser</role-name>
	</auth-constraint>
</security-constraint>

url-pattern 节点定义网站内需要授权访问的资源或目录,role-name 节点定义授权的规则。

3. 设置网站验证方式

在上一步的 </security-constraint> 节点下方加入

<!-- 为网站定义验证方式 -->
<login-config>
<auth-method>BASIC</auth-method>
<realm-name>testwww Application</realm-name>
</login-config>

4. 配置授权用户

打开 Tomcat 用户配置文件 <TOMCAT_HOME>/conf/tomcat-users.xml,在 <user> 节点中加入

<user name="username" password="password" roles="thetestuser" />

namepassword 分别为你要为网站设置的登录用户的用户名及密码,此处的 roles 属性对应步骤 2 中的 <role-name>

5. 重启 Tomcat

重启后打开网站 http://localhost:8080/testwww/,如果以上配置都正确,应该会弹出登录窗口,输入步骤 4 中配置的用户名及密码即可正常访问网站。

  • Apache
    27 引用 • 34 回帖
  • Tomcat

    Tomcat 最早是由 Sun Microsystems 开发的一个 Servlet 容器,在 1999 年被捐献给 ASF(Apache Software Foundation),隶属于 Jakarta 项目,现在已经独立为一个顶级项目。Tomcat 主要实现了 JavaEE 中的 Servlet、JSP 规范,同时也提供 HTTP 服务,是市场上非常流行的 Java Web 容器。

    162 引用 • 529 回帖 • 2 关注
  • htaccess
    2 引用

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...