programing

React 경로용 Apache 서버 설정 방법

kingscode 2023. 3. 22. 22:50
반응형

React 경로용 Apache 서버 설정 방법

로컬 개발 서버에서 리액트 앱이 제대로 실행되고 있지만 실제 가동 가능한 파일을 Apache의 htdocs 디렉토리에 직접 덤프하면 작동하지 않습니다.

제가 가지고 있는 것은 다음과 같습니다.

/var/www/index.html
/var/www/bundle.js

그리고 나는 그렇게 했다.

DocumentRoot /var/www

/etc/syslog2/syslog-available/000-default.conf에 추가되어 있습니다.


1) 로그인 페이지로 라우팅한http://...com/액세스 했을 때
후 2) 크크 2 2 2 2 2 2 2 2 2 2

<Link to="main"><button>Log In</button></Link>

브라우저 위치 필드의 내용은 다음과 같습니다.

http://...com/main

3) 이 URL(http://...com/main)을 새로고침하면

The requested URL /main was not found on this server

리액트에서의 마이마운트:

    <Router history={browserHistory }>
      <Route path="/" component={TopContainer}>
          <IndexRoute component={Login} />
          <Route path='main' component={MainContainer} />   
      </Route>
</Router>

Apache 구성에서 부족한 다른 점은 무엇입니까?

감사해요.

VirtualHost 구성을 변경합니다(일반적으로 에 있습니다)./etc/httpd/conf.d\vhosts.conf에 Rewrite*

<VirtualHost *:8080>
  ServerName example.com
  DocumentRoot /var/www/httpd/example.com

  <Directory "/var/www/httpd/example.com">
    ...

    RewriteEngine On
    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    # Rewrite everything else to index.html to allow html5 state links
    RewriteRule ^ index.html [L]
  </Directory>
</VirtualHost>

에게 존재하는 모든 Apache 파일을 합니다./index.html가 a a 404: not found.

여기에서 감사히 도난당한 완전한 답변

편집: 현재 Apache 버전에서는 'On'이 대문자여야 합니다.

위의 솔루션은 Ubuntu에서도 동작합니다만, 조금 고생하고 있기 때문에, 동작시키기 위해서 필요한 순서는 다음과 같습니다.

상기의 설정을 배치할 필요가 있는 파일의 장소는,

/etc/apache2/sites-enabled

기본값은 입니다.

/etc/apache2/sites-enabled/000-default.conf

그런 다음 Rewrite Engine이 실행 중인지 확인해야 합니다(그렇지 않으면 Apache 서버를 재시작할 때 오류가 발생합니다).

sudo a2enmod rewrite

마지막으로 Apache 서버를 재시작합니다.

sudo /etc/init.d/apache2 restart

이제, 효과가 있을 거야.

하고 있는 웹는 「」아래)./var/www/html

<Directory "/var/www/html">
    RewriteEngine on
    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    # Rewrite everything else to index.html to allow html5 state links
    RewriteRule ^ index.html [L]
</Directory>

의 「」아래의 할 수 있습니다.<VirtualHost ...>

.htaccess와 서브디렉토리를 사용할 필요가 있는 경우는, 다음과 같이 해 주세요.

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

여기 있는 많은 답변과 코멘트를 반영하여 나에게 효과가 있었던 것은 다음과 같다.

  1. sudo a2enmod rewrite
  2. [ ] [ ]를./etc/apache2/apache2.conf
  3. 루트 경로와 함께 붙여넣기:
<Directory "/var/www/PATH_TO_YOUR_ROOT">
    RewriteEngine on
    # Don't rewrite files or directories
    RewriteCond %{REQUEST_FILENAME} -f [OR]
    RewriteCond %{REQUEST_FILENAME} -d
    RewriteRule ^ - [L]
    # Rewrite everything else to index.html to allow html5 state links
    RewriteRule ^ index.html [L]
</Directory>
  1. sudo service apache2 restart

사이트 고유의 conf 파일에 붙여넣기는 이전 답변대로 작동하지 않았습니다.

지금까지 게시된 솔루션 중 누락된 리소스가 404가 아닌 200을 잘못 반환하는 문제를 해결할 수 있는 솔루션은 없는 것 같습니다.이 때문에 특정 파일이 누락된 경우 디버깅이 다소 번거로울 수 있습니다.

할 때 는 HTML을 합니다), 은 어떤 받을 입니다.text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8그러나 첫 번째 로드 후 리소스에 액세스할 때는 그렇지 않습니다(JS 파일을 통해 Import됨).<script>또는 ES6 모듈이 요구하는 대로*/*, CSS 파일에는text/css,*/*;q=0.1, 경유로 JSON에 액세스 합니다.fetch()API는 다음을 지정합니다.application/json, text/plain, */*등).이 전제조건에 따라 존재하지 않는 파일(Single Page App 내에서만 동작하는 루트 등)에 액세스하려고 할 때 해당 SPA가 이름이 변경된 CSS 파일 또는 누락된 JSON 파일을 요구할 때마다 해당 파일을 전송하지 않고 Single Page App에 서비스를 제공하도록 Apache를 설정할 수 있습니다.

편집: MDN에는 Accept 헤더에 대한 공통목록있습니다.

<Directory  "/var/www/httpd/example.com">
    RewriteEngine on

    # Browsers will specifically ask for HTML (among other things) on initial page load
    # That is, if the *user* tries to access a *nonexisting* URL, the app is loaded instead
    # but if a webpage attempts to load a missing resource it will return 404.
    # (You can still go to /myreactapp/favicon.ico, but a missing /myreactapp/favicon.png resource won't return 200)

    # if (HTTP_ACCESS.contains('text/html') && file_not_exists(REQUEST_FILENAME))
    RewriteCond %{HTTP_ACCEPT} text/html
    RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.html [last]

    # Any ressources loaded by index.html should behave correctly (i.e: Return 404 if missing)
    RewriteRule ^ - [last]

    AllowOverride None
    Options FollowSymLinks Multiviews 
    Require all granted
</Directory>

감사해요!이건 나한테 효과가 있었어.

여러 사이트(가상 호스트)와 SSL 증명서(SSL은 certbot으로 작성)를 서비스하는 경우 설정을 붙여넣고 https로 리다이렉트합니다.

이 설정은 Linode/Ubuntu에서 작동합니다.

yoursite.com-le-ssl.conf

<IfModule mod_ssl.c>
<VirtualHost *:443>
  # Admin email, Server Name (domain name), and any aliases
  ServerAdmin webmaster@yoursite.com
  ServerName  yoursite.com
  ServerAlias www.yoursite.com

  # Index file and Document Root (where the public files are located)
 DirectoryIndex index.html index.php
  DocumentRoot /var/www/html/yoursite.com/public_html 
<Directory  "/var/www/html/yoursite.com/public_html">
    RewriteEngine on

    # Browsers will specifically ask for HTML (among other things) on initial page load
    # That is, if the *user* tries to access a *nonexisting* URL, the app is loaded instead
    # but if a webpage attempts to load a missing resource it will return 404.
    # (You can still go to /myreactapp/favicon.ico, but a missing /myreactapp/favicon.png resource won't return 200)

    # if (HTTP_ACCESS.contains('text/html') && file_not_exists(REQUEST_FILENAME))
    RewriteCond %{HTTP_ACCEPT} text/html
    RewriteCond %{REQUEST_FILENAME} !-f
        RewriteRule ^ index.html [last]

    # Any ressources loaded by index.html should behave correctly (i.e: Return 404 if missing)
    RewriteRule ^ - [last]

    AllowOverride None
    Options FollowSymLinks Multiviews 
    Require all granted
</Directory>
  # Log file locations
  LogLevel warn
  ErrorLog  /var/www/html/yoursite.com/log/error.log
  CustomLog /var/www/html/yoursite.com/log/access.log combined
Include /etc/letsencrypt/options-ssl-apache.conf
SSLCertificateFile /etc/letsencrypt/live/yoursite.com/fullchain.pem
SSLCertificateKeyFile /etc/letsencrypt/live/yoursite.com/privkey.pem
</VirtualHost>
</IfModule>

이것은 우리가 직장에서 사용하고 있는 프로덕션 리액션 앱에서 사용하는 것입니다.BrowserRouter부터react-router:

httpd.conf

<VirtualHost *:3000>
    DocumentRoot "/var/www/html"

    <Directory /var/www/html/>
        Header set Cache-Control "no-cache"
        # https://stackoverflow.com/a/34154531/2089675
        FallbackResource /index.html
    </Directory>

    <Directory /var/www/html/static/>
        # https://create-react-app.dev/docs/production-build/#static-file-caching
        Header set Cache-Control "public, max-age=31536000"
        # https://stackoverflow.com/a/54943214/5600537
        RequestHeader edit "If-None-Match" '^"((.*)-gzip)"$' '"$1", "$2"'
    </Directory>
</VirtualHost>

여기 댓글의 대부분은 SO의 답변이 있기 때문에 그냥 돌려드립니다.


배열

위의 파일을 다음 위치에 배치합니다./usr/local/apache2/conf/httpd.conf.

또, 이 설정에서는, 의 내용이 보존되어 있는 것을 전제로 하고 있습니다.build내부 폴더/var/www/html/다른 곳에 배치한 경우 경로를 적절히 조정합니다.

포트

VirtualHost *:3000부품은 도커 컨테이너 내의 서버 포트를 노출하기 위한 것입니다(httpd:buster)가 실행되었습니다.이 포트도 CRA가 디폴트로 dev로 설정되어 있는 포트와 동일합니다.외부 프록시는 응용 프로그램에 액세스할 수 있는 위치를 관리하는 데 사용됩니다.

압축

마지막으로 gzipped 파일 제공에 관심이 있는 경우 다음 파일을 삭제할 수 있습니다.RequestHeader edit라인업하고 나서 확실히 하기 위해 몇 가지 작업을 더 합니다..gz파일 서비스 가능:

예를 들어,

AddOutputFilterByType DEFLATE text/html application/javascript

ubantu 서버에서 리액트 라우팅 문제가 해결되었습니다.

솔루션:

  1. 콘솔을 사용하여 파일을 엽니다.

SSL nano /etc/apache2/sites-available/000-default-le-ssl.conf 를 사용하는 경우

다음 행을 추가합니다.

===================================================================================

DocumentRoot /var/www/project <디렉토리 "/var/www/project"> RewriteEngine on RewriteCond %{HTTP_ACCEPT} 텍스트/html RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.html [ last ]RewriteRule ^ - [ last ]

AllowOverride None
Options FollowSymLinks Multiviews 
Require all granted

솔루션:

Options -MultiViews
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.html [QSA,L]

복수의 가상 호스트가 있는 경우는, 다음의 순서에 따릅니다.

  • 해당 VH로 이동하여 .htaccess 파일을 엽니다.
  • 이 행을 추가하여 저장하다
  • Apache 서비스를 다시 시작하여 설정에 반영되도록 합니다.

이 디렉토리로 이동

  1. /etc/syslog2/syslog-available

  2. 파일: 000-default.conf 를 엽니다.

  3. 권한 변경: 777

  4. 파일 하단에 코드 붙여넣기

RewriteEngine on 

# Don't rewrite files or directories 

RewriteCond %{REQUEST_FILENAME} -f [OR] 

RewriteCond %{REQUEST_FILENAME} -d 

RewriteRule ^ - [L] 

# Rewrite everything else to index.html to allow html5 state links 

RewriteRule ^ index.html [L] 

  1. 서버 재시작

언급URL : https://stackoverflow.com/questions/44038456/how-to-setup-apache-server-for-react-route

반응형