如何使用Nginx在同一台服务器上部署后端和前端但路径不同
How to deploy backend and frontend on the same server but different path with Nginx
我需要在 https://service.domain.it and the backend in https://service.domain.it/api 中部署前端。
我已经完成了部署配置,但我遇到了 spring 安全 + JWT 身份验证的麻烦。这是WebSecurityConfigurerAdapter
的配置方法
@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/public/**").permitAll() //login/logout/recoverypassw
.antMatchers("/user/**").hasAnyRole("USER","ADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).
and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
这是 nginx 配置
#service.domain.it
server{
listen 443 ssl;
server_name service.domain.it;
ssl_certificate /etc/letsencrypt/live/service.domain.it/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/service.domain.it/privkey.pem;
location /api/ {
#backend
proxy_pass http://localhost:8085;
}
location / {
#frontend
index index.html;
alias /var/www/html/Service/;
}
}
server{
listen 80;
server_name service.domain.it;
return 301 https://service.domain.it$request_uri;
}
我该怎么办?
您的后端服务不理解您 proxy_configuration 中使用的 /api
。您必须在将 URI 发送到后端之前重写它。
location /api {
rewrite ^/api/(.*) / break;
proxy_pass http://backend/;
}
这将在将 URI 发送到后端之前从 URI 中删除 /api
。
我需要在 https://service.domain.it and the backend in https://service.domain.it/api 中部署前端。 我已经完成了部署配置,但我遇到了 spring 安全 + JWT 身份验证的麻烦。这是WebSecurityConfigurerAdapter
的配置方法@Override
public void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/public/**").permitAll() //login/logout/recoverypassw
.antMatchers("/user/**").hasAnyRole("USER","ADMIN")
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and().exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).
and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
and().addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
这是 nginx 配置
#service.domain.it
server{
listen 443 ssl;
server_name service.domain.it;
ssl_certificate /etc/letsencrypt/live/service.domain.it/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/service.domain.it/privkey.pem;
location /api/ {
#backend
proxy_pass http://localhost:8085;
}
location / {
#frontend
index index.html;
alias /var/www/html/Service/;
}
}
server{
listen 80;
server_name service.domain.it;
return 301 https://service.domain.it$request_uri;
}
我该怎么办?
您的后端服务不理解您 proxy_configuration 中使用的 /api
。您必须在将 URI 发送到后端之前重写它。
location /api {
rewrite ^/api/(.*) / break;
proxy_pass http://backend/;
}
这将在将 URI 发送到后端之前从 URI 中删除 /api
。