首页 > 解决方案 > 从 Apache 访问静态 Spring Boot 文件

问题描述

我有一个具有这种配置的 Apache Web 服务器:

<VirtualHost *:80>
  # Admin email, Server Name (domain name), and any aliases
  ServerAdmin webmaster@elcor.com
  ServerName  elcor.com
  ServerAlias www.elcor.com
  ProxyPass / http://localhost:8080/home.html
  ProxyPassReverse / http://localhost:8080/html

  # Index file and Document Root (where the public files are located)
  DirectoryIndex index.html index.php
  DocumentRoot /var/www/html/elcor.com/public_html
  # Log file locations
  LogLevel warn
  ErrorLog  /var/www/html/elcor.com/log/error.log
  CustomLog /var/www/html/elcor.com/log/access.log combined
</VirtualHost>

当我直接使用 访问 Spring Boot 应用程序时http://localhost:8080/home.html,一切都很好,但是当我通过 Apache Web 服务器 ( http://elcor.com) 执行此操作时,我在 Spring Boot 安全文件中定义的所有公共匹配器 ( *.css, *.js..) 不再是公共的,它会重定向登录这些文件。

@Override
protected void configure(HttpSecurity http) throws Exception {
        
    http
        .authorizeRequests()
            .antMatchers(publicMatchers()).permitAll()
            .anyRequest().authenticated()
            .and()
        .formLogin()
            .loginPage("/login.html")
            .defaultSuccessUrl("/joan.html")
            .failureUrl("/login.html?error").permitAll()
            .and()
        .logout().permitAll();
}

标签: javaspring-bootapachespring-mvcspring-security

解决方案


由于您的 Spring 应用程序还为您的静态资源、js 和 CSS 提供服务,因此您需要以一种允许您将流量路由到应用程序的方式配置 Apache,以便找到这些资源。

请在您的 Apache 配置中尝试此更改:

ProxyPass / http://localhost:8080
ProxyPassReverse / http://localhost:8080

如您所见,这个想法是将在您的网络服务器的根路径中接收到的所有流量路由到您的 Spring 应用程序。

我认为此更改可能有助于解决您的问题。

此外,您可以指示 Spring Security 忽略此类资源。您可以通过覆盖此方法在 Spring Security 配置类中实现此功能:

@Override
public void configure(WebSecurity web) throws Exception {
  web
    .ignoring()
       // You can also ignore other resources like images, fonts, etcetera
      .antMatchers("/**/*.js")
      .antMatchers("/**/*.css");
}

推荐阅读