Jekyll, Hugo 또는 Pelican과 같은 정적 사이트 생성기로 생성된 정적 웹 사이트를 호스팅하는 몇 가지 저렴한 방법이 있습니다. 이 전체 블로그는 Jekyll을 사용하여 정적으로 생성됩니다. 그러나 위의 옵션 중 어느 것도 사용할 수 없습니다. 왜냐하면 이 블로그를 운영하는 동안 도메인 이름, URL 스키마, 게시물 이름을 변경했기 때문입니다. 모든 이전 URL을 활성 상태로 유지 저는 Apache를 사용하여 이 블로그를 호스팅하고 있으며 최근에는 단일 가상 머신에서 nginx를 사용하고 있으며 두 소프트웨어의 리디렉션 기능이 제대로 작동하지만 새롭고 다른 곳에서 호스팅할 준비가 되었습니다. 이전 게시물에서는 Google App Engine 및 Python을 사용하여 이전 도메인에서 새 도메인으로 URL을 리디렉션하는 방법을 설명했지만 이제는 정적 콘텐츠를 제공하는 방법이 필요했습니다. **및** 동일한 도메인의 URL을 리디렉션합니다. 동일한 도메인 리디렉션 요구 사항 때문에 단순히 Google App Engine의 정적 콘텐츠 전용 기능(위 목록에 링크됨)을 사용할 수 없습니다. 그러나 Google App Engine을 간단한 Golang 애플리케이션과 함께 사용하여 정적 콘텐츠 **및** 동일한 도메인 리디렉션을 모두 제공할 수 있습니다. ## 왜 Google App Engine인가? 게시물의 나머지 부분을 살펴보기 전에 Google App Engine에서 블로그를 호스팅하는 이유가 궁금할 것입니다. 이유는 다음과 같습니다. - 트래픽이 App Engine의 프리 티어인 28인스턴스 시간과 일일 1GB의 이그레스 트래픽에 해당하는 경우 블로그 호스팅은 거의 무료입니다. -업데이트 푸시는 하나의 명령으로 수행됩니다 - Stackdriver를 사용하여 로깅 및 모니터링 통합 - 트래픽 패턴에 따른 자동 업/다운 스케일링 - 몇 번의 클릭만으로 웹 로그를 장기 저장 및 임시 분석을 위해 BigQuery와 같은 것으로 쉽게 푸시할 수 있습니다. - LetâÃÂÃÂs Encrypt를 사용하여 관리되는 SSL 인증서 ## 전제 조건 이 게시물은 다음을 가정합니다. - Google Cloud Platform(GCP)에 익숙하고 이미 GCP 프로젝트를 생성한 경험이 있는 분 - Google Cloud SDK를 설치했습니다. - 당신은 인증했습니다 Google 계정에 대한 gcloudcommand GCP 프로젝트 만들기 아직 생성하지 않은 경우 **GCP 프로젝트는 다음 단계를 따릅니다. - 웹 브라우저를 열고 Google 계정을 만들거나 로그인합니다. - GCP 콘솔로 이동 - 첫 번째 GCP 프로젝트인 경우 GCP 프로젝트를 만들라는 메시지가 표시됩니다. 각 Google 계정에는 12개월 이내에 GCP에 사용할 수 있는 $300의 크레딧이 제공됩니다. GCP 프로젝트를 생성하려면 신용카드를 입력해야 하지만 $300 크레딧이 소진되거나 12개월이 만료될 때까지 청구되지 않습니다. - 새 GCP 프로젝트인 경우 GCP 콘솔의 Compute Engine 섹션으로 이동하여 Compute Engine API를 사용 설정하고 초기화가 완료될 때까지 기다려야 합니다. Google 클라우드 SDK 설치 아직 설치하지 않은 경우 **Google Cloud SDK는 여기의 안내를 따르세요. gcloud 인증 GCP 프로젝트를 만들고 Google Cloud SDK를 설치했으면 마지막 단계는 gcloud 명령을 Google 계정에 추가합니다. 터미널 애플리케이션을 열고 다음 명령을 실행합니다. gcloud 인증 로그인 웹 페이지가 웹 브라우저에서 열립니다. Google 계정을 선택하고 GCP 액세스 권한을 부여합니다. 완료되면 인증되고 진행할 준비가 됩니다. ## 디렉토리 생성 다음으로 워크스테이션 어딘가에 Google App Engine 애플리케이션을 저장할 디렉토리를 만듭니다. mkdir ~/Sites/example.com/app_engine 해당 디렉터리로 변경합니다. cd ~/Sites/example.com/app_engine 이 게시물의 나머지 부분에서는 이 디렉터리 내에서 작업하고 있다고 가정합니다. 또한 내부에 디렉토리를 생성하십시오. **정적이라는 **app_engine** 디렉토리 mkdir ~/Sites/example.com/app_engine/static 나중에 이 디렉토리를 다시 방문하게 됩니다. ## app.yaml 생성 Google App Engine에는 일반적으로 두 개의 파일이 필요합니다. **app.yaml** 및 Python, Golang, Java 또는 PHP로 작성된 **응용 프로그램 파일** - 이 경우 Golang이 됩니다. **app.yaml**은 애플리케이션을 실행하는 데 필요한 구성을 제공합니다. **app.yaml에는 다양한 매개변수가 존재할 수 있습니다. 이러한 매개변수는 사용되는 프로그래밍 언어에 따라 다를 수 있습니다. 이 게시물에서는 Golang이 사용되며 여기에서 사용 가능한 모든 Golang 매개 변수를 찾을 수 있습니다. 파일 생성 **app.yaml** 다음 내용: 런타임: go api_version: go1 핸들러: - url:script: _go_app 보안: 항상 redirect_http_response_code: 301 그것을주의해라 **보안: 항상**이 설정되었습니다. 이는 Golang 애플리케이션이 항상 HTTPS를 통해 제공됨을 의미합니다. 최종 사용자가 HTTP를 통해 웹 애플리케이션으로 이동하면 기본적으로 HTTPS 버전으로 302 리디렉션됩니다. 이것이 **redirect_http_response_code: 301**도 설정한 이유입니다. 저는 항상 웹 애플리케이션이 HTTPS를 통해 제공되기를 원하고 검색 엔진이 HTTP에서 HTTPS로의 리디렉션을 임시 리디렉션으로 해석하는 것을 원하지 않습니다. 영구 리디렉션입니다. 정적 자산이 있고 아마도 그럴 가능성이 있는 경우 App Engine에 이를 알리고 애플리케이션이 아닌 개체 스토리지에서 해당 자산을 제공하도록 하는 것이 가장 좋습니다. 이 작업은 쉽고 다음을 통해서도 수행됩니다. **app.yaml** 파일 예를 들어 favicon 파일, CSS 디렉토리, Javascript 디렉토리 및 이미지 디렉토리가 있는 경우 다음을 사용하십시오. **app.yaml** 파일: 런타임: go api_version: go1 핸들러: - url: /favicon.png$ static_files: static/favicon.png 업로드: static/favicon.png - url: /css static_dir: static/css - url: /js static_dir: static/js - url: /images static_dir: 정적/이미지 - url:script: _go_app 보안: 항상 redirect_http_response_code: 301 ## main.go 만들기 다음으로 Golang 애플리케이션 파일이 필요합니다. 다음 코드가 필요에 맞게 파일을 생성하려면 **main.go 아래 코드를 복사하여 붙여넣고 다음과 같이 수정합니다. - 에서 domainvariable, 도메인 이름이 올바른 HTTP 프로토콜과 일치하도록 값을 변경합니다. - 에서 urlsmap에서 필요한 리디렉션과 일치하도록 모든 키 값 쌍을 바꿉니다. 각 키를 현재 도메인의 경로 부분(httpsexample.com/example-post-1.html 대신 /example-post-1.html)으로 바꾸십시오. 살아 유지. 그런 다음 각 값을 리디렉션하려는 현재 도메인의 새 URL 경로 부분으로 바꿉니다. 모든 리디렉션은 301 리디렉션이 됩니다. 이것은 변경하여 수정할 수 있습니다. 아래 코드에서 **301**을 **302**와 같은 다른 HTTP 리디렉션 상태 코드로 package main import ( "net/http""os""strings") func init() { http.HandleFunc handler) } func handler(w http.ResponseWriter, r *http.Request) { // 요청이 있으면 True(확인) 경로는 값인 경우 URL 맵에 있습니다. ok := urls[r.URL.Path]; ok { value = domain + value http.Redirect(w, r, value, 301) } else { path := "static/"+ r.URL.Path // HTTP 요청이 존재하고 수행하는 디렉토리에 대한 경우 403 반환 f, err := os.Stat(path)인 경우 index.html 파일을 포함하지 않음; err == nil&& f.IsDir() { index := strings.TrimSuffix(path,+ "/index.html"if _, 오류 := os.Open(index); 오류 != nil { w.WriteHeader (403) w.Writebytehtml> 403 금지됨

403 Forbidden

return } } // Return custom 404 page if HTTP request is to a non-existent file if _, err := os.Stat(path); os.IsNotExist(err) { w.WriteHeader(404) http.ServeFile(w, r, "static/404.html") return // Withoutreturn, a "404 page not found" string will be displayed at the bottom of your custom 404 page } http.ServeFile(w, r, path) return } } var domain string = "httpsexample.com" var urls = map[string]string{ "/example-post-1.html": "/post/example-post-1.html", "/example-post-2.html": "/post/example-post-2.html", "/example-post-3.html": "/post/example-post-3.html", } ## Generate the Static Content With **app.yaml** and **main.go** saved, the last piece is to generate your static content and store it in the **static** directory you created earlier How you do this entirely depends on what static site generator you are using If you are using Jekyll, you can configure the **destination** parameter in Jekyll’s _ **config.yml** file to save your static content in any directory on your workstation. So, you could set the **destination** parameter to Sites/example.com/app_engine/static and, every time you run jekyll build, the static content will be saved in that directory ## Deploy to App Engine With **app.yaml **main.go and your static content generated, you are ready to deploy your Google App Engine application Assuming gcloud is already pointed at the Google Cloud Project you want to deploy to, verify with gcloud config list project, run the following command: gcloud app deploy The command will output the appspot URL your application will be deployed to and ask if you want to continue. Typically, the appspot URL is **httpsyour-project-id.appspot.com This is also a useful self-check to make sure you are not deploying your application to the wrong Google Cloud Project. If everything looks okay, type **Y** and **Enter** to deploy your application. Depending on how large your static content is, your application should be deployed within about one minute ## Setup DNS At this point, your application is deployed under URL **httpsyour-project-id.appspot.com Unless your website uses that as its domain name, you will probably want to setup a custom domain that uses your actual current domain name The App Engine section of the Google Cloud Console can be used to do this. Go here and follow the instructions to configure your custom domain Once that is complete and DNS has had time to propagate, you should be able to navigate in your web browser to one of your current domain’s old URLs, for example **httpsexample.com/example-post-1.html and have it redirect to your current domain’s new URLs, for example **httpsexample.com/post/example-post-1.html** ## Pushing Updates To push updates, make the necessary changes in your static site’s source directory, regenerate the static content, and redeploy to Google App Engine by changing into the Sites/example.com/app_engine** directory and running gcloud app deploy ## References - A Surprising Feature of Golang that Colored Me Impressed - How to check if a map contains a key in go? - Disable directory listing with http.FileServer - 3 Ways to Disable http.FileServer Directory Listings - Handling HTTP Request Errors in GO - HTTP and Error management in Go - please add ability to set custom 404 notFoundHandler for http.FileServer