Skip to content

Commit 5c9776b

Browse files
committed
fix(nginx): move htpasswd files out of sites-enabled directory
Nginx includes all files from sites-enabled, not just *.conf. Htpasswd files placed there caused nginx -t to fail, preventing config creation for new domains. - Store htpasswd in /etc/nginx/htpasswd/ instead of sites-enabled - Auto-create htpasswd directory on first use - Clean up stale htpasswd files from sites-enabled on startup
1 parent 4dd71c6 commit 5c9776b

1 file changed

Lines changed: 26 additions & 1 deletion

File tree

internal/nginx/service.go

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,9 @@ func (s *Service) SyncConfigs() error {
3434
return nil
3535
}
3636

37+
// Migrate: remove stale htpasswd files from sites-enabled (they belong in htpasswd dir)
38+
s.cleanupStaleHtpasswd()
39+
3740
domains, err := s.repo.GetAll()
3841
if err != nil {
3942
return fmt.Errorf("get domains: %w", err)
@@ -235,8 +238,12 @@ func (s *Service) configPath(domain string) string {
235238
return filepath.Join(s.sitesDir, fmt.Sprintf("sc_%s.conf", domain))
236239
}
237240

241+
func (s *Service) htpasswdDir() string {
242+
return filepath.Join(filepath.Dir(s.sitesDir), "htpasswd")
243+
}
244+
238245
func (s *Service) htpasswdPath(domain string) string {
239-
return filepath.Join(s.sitesDir, fmt.Sprintf("sc_%s.htpasswd", domain))
246+
return filepath.Join(s.htpasswdDir(), fmt.Sprintf("sc_%s.htpasswd", domain))
240247
}
241248

242249
func (s *Service) writeAndReload(domain *Domain) error {
@@ -284,6 +291,9 @@ func (s *Service) writeAndReload(domain *Domain) error {
284291
}
285292

286293
func (s *Service) writeHtpasswd(domain *Domain) error {
294+
if err := os.MkdirAll(s.htpasswdDir(), 0755); err != nil {
295+
return fmt.Errorf("create htpasswd dir: %w", err)
296+
}
287297
hash, err := bcrypt.GenerateFromPassword([]byte(domain.BasicAuthPassword), bcrypt.DefaultCost)
288298
if err != nil {
289299
return fmt.Errorf("hash password: %w", err)
@@ -296,6 +306,21 @@ func (s *Service) removeConfig(domain string) {
296306
os.Remove(s.configPath(domain))
297307
}
298308

309+
// cleanupStaleHtpasswd removes htpasswd files that were incorrectly placed in sites-enabled.
310+
func (s *Service) cleanupStaleHtpasswd() {
311+
entries, err := os.ReadDir(s.sitesDir)
312+
if err != nil {
313+
return
314+
}
315+
for _, e := range entries {
316+
if strings.HasSuffix(e.Name(), ".htpasswd") {
317+
old := filepath.Join(s.sitesDir, e.Name())
318+
slog.Info("removing stale htpasswd from sites-enabled", "file", old)
319+
os.Remove(old)
320+
}
321+
}
322+
}
323+
299324
func (s *Service) removeHtpasswd(domain string) {
300325
os.Remove(s.htpasswdPath(domain))
301326
}

0 commit comments

Comments
 (0)