Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feature: supports deploying memos to a subfolder of the domain name. #3845

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
all:
make build_frontend
make build_backend

build_init:
cd ./web/ && pnpm i --frozen-lockfile && cd ../

build_proto:
cd ./proto/ && npx buf generate && cd ../

build_frontend:
cd ./web/ && pnpm run build && cd ../
sed -i "s|<script type=\"module\" crossorigin src=\"|&{{ .baseurl }}|g" ./web/dist/index.html
sed -i "s|<link rel=\"stylesheet\" crossorigin href=\"|&{{ .baseurl }}|g" ./web/dist/index.html
rm -rf ./server/router/frontend/dist/*
cp -R ./web/dist/* ./server/router/frontend/dist/

build_backend:
CGO_ENABLED=0 go build -o memos ./bin/memos/main.go

build_backend_armv7l:
CGO_ENABLED=0 GOOS=linux GOARCH=arm GOARM=7 go build -o memos.armv7l ./bin/memos/main.go

build_backend_arm64:
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -o memos.arm64 ./bin/memos/main.go

clean_frontend:
rm -rf ./web/dist/
37 changes: 37 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,43 @@ docker run -d --name memos -p 5230:5230 -v ~/.memos/:/var/opt/memos neosmemo/mem

Learn more about [other installation methods](https://www.usememos.com/docs/install).

## Deploy under a subdirectory of the domain

1. If you want to deploy memos to a subdirectory, you need to configure base-url (via environment variables or parameters when executing memos).
For example, if you want to deploy memos in the /memos subdirectory of the domain, run the following command(memos is installed in /usr/local/bin):
```bash
MEMOS_MODE="prod" MEMOS_PORT=5230 /usr/local/bin/memos --base-url /memos
```
or
```bash
MEMOS_MODE="prod" MEMOS_PORT=5230 MEMOS_BASE_URL=/memos /usr/local/bin/memos
```

2. nginx need add config item, like this:
```
location ^~ /memos/ {
# Note: The reverse proxy backend URL needs to have a path symbol at the end
proxy_pass http://127.0.0.1:5230/;

proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header REMOTE-HOST $remote_addr;
proxy_set_header X-Forwarded-For $remote_addr; # Set the request source address
proxy_set_header X-Forwarded-Proto $scheme; # Set Http protocol
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
add_header X-Cache $upstream_cache_status;
add_header Cache-Control no-cache;
}
```

Of course, there is a slight requirement when compiling the memos frontend. You need to execute the sed command to modify the index.html of the frontend after compiling the frontend (the corresponding command is already included in the Makefile).
```bash
sed -i "s|<script type=\"module\" crossorigin src=\"|&{{ .baseurl }}|g" ./web/dist/index.html
sed -i "s|<link rel=\"stylesheet\" crossorigin href=\"|&{{ .baseurl }}|g" ./web/dist/index.html
```

## Contribution

Contributions are what make the open-source community such an amazing place to learn, inspire, and create. We greatly appreciate any contributions you make. Thank you for being a part of our community! 🥰
Expand Down
11 changes: 10 additions & 1 deletion bin/memos/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ var (
DSN: viper.GetString("dsn"),
InstanceURL: viper.GetString("instance-url"),
Version: version.GetCurrentVersion(viper.GetString("mode")),
BaseURL: viper.GetString("base-url"),
}
if err := instanceProfile.Validate(); err != nil {
panic(err)
Expand Down Expand Up @@ -110,6 +111,7 @@ func init() {
rootCmd.PersistentFlags().String("driver", "sqlite", "database driver")
rootCmd.PersistentFlags().String("dsn", "", "database source name(aka. DSN)")
rootCmd.PersistentFlags().String("instance-url", "", "the url of your memos instance")
rootCmd.PersistentFlags().String("base-url", "", "the base url of your memos instance")
eaglexmw-gmail marked this conversation as resolved.
Show resolved Hide resolved

if err := viper.BindPFlag("mode", rootCmd.PersistentFlags().Lookup("mode")); err != nil {
panic(err)
Expand All @@ -132,12 +134,18 @@ func init() {
if err := viper.BindPFlag("instance-url", rootCmd.PersistentFlags().Lookup("instance-url")); err != nil {
panic(err)
}
if err := viper.BindPFlag("base-url", rootCmd.PersistentFlags().Lookup("base-url")); err != nil {
panic(err)
}

viper.SetEnvPrefix("memos")
viper.AutomaticEnv()
if err := viper.BindEnv("instance-url", "MEMOS_INSTANCE_URL"); err != nil {
panic(err)
}
if err := viper.BindEnv("base-url", "MEMOS_BASE_URL"); err != nil {
panic(err)
}
}

func printGreetings(profile *profile.Profile) {
Expand All @@ -150,8 +158,9 @@ addr: %s
port: %d
mode: %s
driver: %s
baseurl: %s
---
`, profile.Version, profile.Data, profile.DSN, profile.Addr, profile.Port, profile.Mode, profile.Driver)
`, profile.Version, profile.Data, profile.DSN, profile.Addr, profile.Port, profile.Mode, profile.Driver, profile.BaseURL)

print(greetingBanner)
if len(profile.Addr) == 0 {
Expand Down
2 changes: 2 additions & 0 deletions server/profile/profile.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ type Profile struct {
Version string
// InstanceURL is the url of your memos instance.
InstanceURL string
// BaseURL is the base url of your memos instance.
BaseURL string
}

func (p *Profile) IsDev() bool {
Expand Down
61 changes: 57 additions & 4 deletions server/router/frontend/frontend.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package frontend
import (
"context"
"embed"
"html/template"
"io"
"io/fs"
"net/http"

Expand All @@ -29,18 +31,69 @@ func NewFrontendService(profile *profile.Profile, store *store.Store) *FrontendS
}
}

func (*FrontendService) Serve(_ context.Context, e *echo.Echo) {
var baseURL = ""

func indexHander(c echo.Context) error {
// open index.html
file, err := embeddedFiles.Open("dist/index.html")
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
defer file.Close()
// render it.
b, err := io.ReadAll(file)
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}

c.Response().WriteHeader(http.StatusOK)
tmpl, err := template.New("index.html").Parse(string(b))
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}
err = tmpl.Execute(c.Response().Writer, map[string]any{
"baseurl": baseURL,
})
if err != nil {
return c.String(http.StatusInternalServerError, err.Error())
}

return nil
}

func (f *FrontendService) Serve(_ context.Context, e *echo.Echo) {
skipper := func(c echo.Context) bool {
return util.HasPrefixes(c.Path(), "/api", "/memos.api.v1")
pathTmp := c.Path()
return pathTmp == "/" || pathTmp == "/index.html" || util.HasPrefixes(pathTmp, "/api", "/memos.api.v1")
}

e.GET("/", indexHander)
e.GET("/index.html", indexHander)
// save baseUrl from profile.
baseURL = f.Profile.BaseURL

// Use echo static middleware to serve the built dist folder.
// Reference: https://github.com/labstack/echo/blob/master/middleware/static.go
e.Use(middleware.StaticWithConfig(middleware.StaticConfig{
HTML5: true,
HTML5: false,
Filesystem: getFileSystem("dist"),
Skipper: skipper,
}))
}), func(skipper middleware.Skipper) echo.MiddlewareFunc {
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
// skip
if skipper(c) {
return next(c)
}
// skip assets
if util.HasPrefixes(c.Path(), "/assets") {
return next(c)
}
// otherwise (NotFound), serve index.html
return indexHander(c)
}
}
}(skipper))
// Use echo gzip middleware to compress the response.
// Reference: https://echo.labstack.com/docs/middleware/gzip
e.Group("assets").Use(middleware.GzipWithConfig(middleware.GzipConfig{
Expand Down
10 changes: 7 additions & 3 deletions web/index.html
Original file line number Diff line number Diff line change
@@ -1,15 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<base href="{{ .baseurl }}">
<meta charset="UTF-8" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" />
<link rel="icon" type="image/webp" href="/logo.webp" />
<link rel="manifest" href="/site.webmanifest" />
<link rel="apple-touch-icon" sizes="180x180" href="{{ .baseurl }}/apple-touch-icon.png" />
<link rel="icon" type="image/webp" href="{{ .baseurl }}/logo.webp" />
<link rel="manifest" href="{{ .baseurl }}/site.webmanifest" />
<meta name="theme-color" media="(prefers-color-scheme: light)" content="#f4f4f5" />
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="#18181b" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
<!-- memos.metadata.head -->
<title>Memos</title>
<script>
window.globalConfig = { BaseUrl: "{{ .baseurl }}"};
</script>
<script>
// Prevent flash of light mode.
const appearance = localStorage.getItem("appearance");
Expand Down
2 changes: 1 addition & 1 deletion web/src/components/MemoActionMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const MemoActionMenu = (props: Props) => {
};

const handleCopyLink = () => {
copy(`${window.location.origin}/m/${memo.uid}`);
copy(`${window.location.origin}` + (window as any).globalConfig.BaseUrl + `/m/${memo.uid}`);
toast.success(t("message.succeed-copy-link"));
};

Expand Down
2 changes: 1 addition & 1 deletion web/src/components/UserAvatar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const UserAvatar = (props: Props) => {
<div className={clsx(`w-8 h-8 overflow-clip rounded-xl`, className)}>
<img
className="w-full h-auto shadow min-w-full min-h-full object-cover dark:opacity-80"
src={avatarUrl || "/full-logo.webp"}
src={avatarUrl || (window as any).globalConfig.BaseUrl + "/full-logo.webp"}
decoding="async"
loading="lazy"
alt=""
Expand Down
2 changes: 1 addition & 1 deletion web/src/grpcweb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { WorkspaceServiceDefinition } from "./types/proto/api/v1/workspace_servi
import { WorkspaceSettingServiceDefinition } from "./types/proto/api/v1/workspace_setting_service";

const channel = createChannel(
window.location.origin,
window.location.origin + (window as any).globalConfig.BaseUrl,
FetchTransport({
credentials: "include",
}),
Expand Down
2 changes: 1 addition & 1 deletion web/src/layouts/RootLayout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const RootLayout = () => {
useEffect(() => {
if (!currentUser) {
if (([Routes.ROOT, Routes.RESOURCES, Routes.INBOX, Routes.ARCHIVED, Routes.SETTING] as string[]).includes(location.pathname)) {
window.location.href = Routes.EXPLORE;
window.location.href = (window as any).globalConfig.BaseUrl + Routes.EXPLORE;
return;
}
}
Expand Down
2 changes: 1 addition & 1 deletion web/src/pages/UserProfile.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ const UserProfile = () => {
return;
}

copy(`${window.location.origin}/u/${encodeURIComponent(user.username)}`);
copy(`${window.location.origin}` + (window as any).globalConfig.BaseUrl + `/u/${encodeURIComponent(user.username)}`);
toast.success(t("message.copied"));
};

Expand Down
Loading