Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

feat(hosting): .htaccess to nginx converter

Juan Denis8ff893a4c81c
diff --git a/backend/app/api/htaccess_tools.py b/backend/app/api/htaccess_tools.py
new file mode 100644
index 00000000..3485c4ea
--- /dev/null
+++ b/backend/app/api/htaccess_tools.py
@@ -0,0 +1,35 @@
+"""Small tools blueprint for .htaccess conversion.
+
+Kept out of apps.py on purpose (separate ownership); intended registration:
+
+ from app.api.htaccess_tools import htaccess_tools_bp
+ app.register_blueprint(htaccess_tools_bp, url_prefix='/api/v1/apps')
+
+which exposes POST /api/v1/apps/htaccess-convert.
+"""
+from flask import Blueprint, jsonify, request
+from flask_jwt_extended import jwt_required
+
+from app.services.htaccess_converter import MAX_INPUT_BYTES, convert
+
+htaccess_tools_bp = Blueprint('htaccess_tools', __name__)
+
+
+@htaccess_tools_bp.route('/htaccess-convert', methods=['POST'])
+@jwt_required()
+def htaccess_convert():
+ """Convert pasted .htaccess text to nginx directives.
+
+ Pure text transform (no server state touched), so any authenticated
+ user may call it. Body: {'htaccess': '<text>'}.
+ """
+ data = request.get_json(silent=True) or {}
+ text = data.get('htaccess')
+ if not isinstance(text, str) or not text.strip():
+ return jsonify({'error': 'htaccess text is required'}), 400
+ if len(text.encode('utf-8', errors='replace')) > MAX_INPUT_BYTES:
+ return jsonify({'error': '.htaccess input exceeds the 256KB limit'}), 413
+ try:
+ return jsonify(convert(text))
+ except ValueError as exc:
+ return jsonify({'error': str(exc)}), 400
diff --git a/backend/app/services/htaccess_converter.py b/backend/app/services/htaccess_converter.py
new file mode 100644
index 00000000..04a3d997
--- /dev/null
+++ b/backend/app/services/htaccess_converter.py
@@ -0,0 +1,809 @@
+"""Convert Apache ``.htaccess`` directives to nginx directives.
+
+Pure text transform behind the "Convert .htaccess" tool next to the per-site
+custom nginx rules editor. The output targets a **server-block include**
+context — ServerKit's generated vhosts are single ``server { }`` blocks and
+custom rules are injected inside them — so no ``server {`` wrappers are ever
+emitted and only directives legal at server/location level are produced.
+
+Everything that cannot be translated is reported in ``unsupported`` with the
+original 1-based line number and a reason. Nothing is silently dropped.
+
+Entry point::
+
+ convert(htaccess_text) -> {
+ 'nginx': str, # pretty-printed nginx directives
+ 'notes': [str], # human guidance about the conversion
+ 'unsupported': [{'line': int, 'directive': str, 'reason': str}],
+ }
+"""
+from __future__ import annotations
+
+import re
+from typing import Dict, List, Optional
+
+# Hard cap on input size (also enforced at the API layer).
+MAX_INPUT_BYTES = 256 * 1024
+
+_INDENT = ' '
+
+# Directives we know about but deliberately do not translate, with tailored
+# reasons. Keys are lowercase first-words.
+_KNOWN_UNSUPPORTED = {
+ 'expiresactive': 'mod_expires has no direct include-level equivalent; use nginx `expires` inside a location block manually',
+ 'expiresbytype': 'mod_expires has no direct include-level equivalent; use nginx `expires` inside a location block manually',
+ 'expiresdefault': 'mod_expires has no direct include-level equivalent; use nginx `expires` inside a location block manually',
+ 'addoutputfilterbytype': 'compression is configured globally via nginx gzip settings, not per-site',
+ 'setoutputfilter': 'compression is configured globally via nginx gzip settings, not per-site',
+ 'browsermatch': 'browser matching for compression is handled by nginx gzip_disable globally',
+ 'php_value': 'PHP settings belong in the PHP-FPM pool config or .user.ini, not nginx',
+ 'php_flag': 'PHP settings belong in the PHP-FPM pool config or .user.ini, not nginx',
+ 'php_admin_value': 'PHP settings belong in the PHP-FPM pool config or .user.ini, not nginx',
+ 'php_admin_flag': 'PHP settings belong in the PHP-FPM pool config or .user.ini, not nginx',
+ 'setenv': 'no nginx equivalent in this context (env vars are set on the app process, not the web server)',
+ 'setenvif': 'no nginx equivalent in this context',
+ 'setenvifnocase': 'no nginx equivalent in this context',
+ 'addtype': 'MIME type mapping is global nginx config (mime.types), not per-site',
+ 'addhandler': 'handler mapping has no nginx equivalent; PHP routing is set up by the vhost template',
+ 'addcharset': 'per-extension charsets have no nginx include-level equivalent',
+ 'fileetag': 'use the nginx `etag` directive manually if needed',
+ 'serversignature': 'controlled globally by nginx server_tokens',
+ 'limitrequestbody': 'use client_max_body_size in the nginx server context (site settings) instead',
+ 'requestheader': 'modifying request headers requires proxy_set_header in the proxy location; not translated automatically',
+ 'authgroupfile': 'nginx basic auth has no group support; use a dedicated htpasswd file per group',
+ 'satisfy': 'nginx combines auth and IP rules with satisfy any/all; set manually if needed',
+ 'checkspelling': 'no nginx equivalent',
+ 'directoryslash': 'no nginx include-level equivalent',
+ 'forcetype': 'use a location block with types/default_type manually',
+ 'rewritemap': 'RewriteMap requires nginx map{} in http context; not available in a per-site include',
+}
+
+
+class _Frame:
+ """A parse context: the root include, a <Files>/<FilesMatch> block, an
+ <IfModule> wrapper, or an opaque unknown <Tag> block."""
+
+ def __init__(self, kind: str, tag: str = '', location: str = '',
+ line: int = 0, raw: str = ''):
+ self.kind = kind # 'root' | 'files' | 'ifmodule' | 'opaque'
+ self.tag = tag # closing-tag name for block frames
+ self.location = location # nginx location matcher for 'files'
+ self.line = line
+ self.raw = raw
+ self.buf: List[str] = [] # emitted nginx lines for this frame
+ # Per-frame access control + auth state, flushed at frame close.
+ self.allows: List[str] = []
+ self.denies: List[str] = []
+ self.deny_all = False
+ self.allow_all = False
+ self.auth_basic = False
+ self.auth_name: Optional[str] = None
+ self.auth_userfile: Optional[str] = None
+ self.require_valid_user = False
+
+
+def _split(line: str) -> List[str]:
+ """Split a directive line on whitespace, honoring double quotes and
+ preserving backslashes (shlex would eat regex escapes)."""
+ parts: List[str] = []
+ buf: List[str] = []
+ in_q = False
+ for ch in line:
+ if ch == '"':
+ in_q = not in_q
+ elif ch.isspace() and not in_q:
+ if buf:
+ parts.append(''.join(buf))
+ buf = []
+ else:
+ buf.append(ch)
+ if buf:
+ parts.append(''.join(buf))
+ return parts
+
+
+def _parse_flags(token: str) -> List[str]:
+ """Parse a trailing ``[R=301,L,NC]`` flags token into a list."""
+ if not (token.startswith('[') and token.endswith(']')):
+ return []
+ return [f.strip() for f in token[1:-1].split(',') if f.strip()]
+
+
+def _normalize_pattern(pattern: str) -> str:
+ """Apache htaccess-context RewriteRule patterns match the URI *without*
+ its leading slash; nginx matches with it. Re-anchor accordingly."""
+ if pattern.startswith('^') and not pattern.startswith('^/'):
+ return '^/' + pattern[1:]
+ return pattern
+
+
+def _normalize_subst(subst: str) -> str:
+ """Ensure relative substitutions get a leading slash for nginx."""
+ if subst and not subst.startswith(('/', 'http://', 'https://', '$', '-')):
+ return '/' + subst
+ return subst
+
+
+def _is_catch_all(pattern: str) -> bool:
+ return pattern in ('.', '.*', '^(.*)$', '(.*)', '^.*$', '^(.*)', '^/?(.*)$')
+
+
+def _wildcard_to_regex(name: str) -> str:
+ """Turn a <Files> glob-ish name into a regex fragment."""
+ escaped = re.escape(name)
+ escaped = escaped.replace(r'\*', '.*').replace(r'\?', '.')
+ return escaped
+
+
+class _Converter:
+ def __init__(self) -> None:
+ self.root = _Frame('root')
+ self.stack: List[_Frame] = [self.root]
+ self.notes: List[str] = []
+ self.unsupported: List[Dict] = []
+ # Pending RewriteCond lines: (lineno, raw, teststring, condpattern)
+ self.conds: List[tuple] = []
+
+ # -- helpers ----------------------------------------------------------
+
+ def _target(self) -> _Frame:
+ """Nearest frame that owns a buffer (root or files)."""
+ for frame in reversed(self.stack):
+ if frame.kind in ('root', 'files'):
+ return frame
+ return self.root
+
+ def note(self, text: str) -> None:
+ if text not in self.notes:
+ self.notes.append(text)
+
+ def flag(self, lineno: int, raw: str, reason: str) -> None:
+ self.unsupported.append(
+ {'line': lineno, 'directive': raw, 'reason': reason})
+
+ def emit(self, lines: List[str], source: Optional[str] = None,
+ lineno: Optional[int] = None) -> None:
+ buf = self._target().buf
+ if buf:
+ buf.append('')
+ if source is not None:
+ where = f' (line {lineno})' if lineno else ''
+ buf.append(f'# from: {source}{where}')
+ buf.extend(lines)
+
+ # -- rewrite handling --------------------------------------------------
+
+ def _flush_dangling_conds(self) -> None:
+ for lineno, raw, _ts, _cp in self.conds:
+ self.flag(lineno, raw, 'RewriteCond without a following RewriteRule')
+ self.conds = []
+
+ def _handle_rewrite_cond(self, lineno: int, raw: str, parts: List[str]) -> None:
+ if len(parts) < 3:
+ self.flag(lineno, raw, 'malformed RewriteCond (expected TestString and CondPattern)')
+ return
+ self.conds.append((lineno, raw, parts[1], parts[2]))
+
+ def _front_controller(self, subst: str) -> Optional[str]:
+ """If pending conds are the classic !-f/!-d filename checks and the
+ substitution is a front controller, return the try_files target."""
+ if not self.conds:
+ return None
+ checks = set()
+ for _ln, _raw, ts, cp in self.conds:
+ if ts.upper() != '%{REQUEST_FILENAME}':
+ return None
+ if cp not in ('!-f', '!-d', '!-l', '!-s'):
+ return None
+ checks.add(cp)
+ if '!-f' not in checks or '!-d' not in checks:
+ return None
+ target = _normalize_subst(subst)
+ if target.endswith('.php'):
+ return f'{target}?$args'
+ if re.search(r'\.\w+$', target):
+ return target
+ return None
+
+ def _https_off_cond(self) -> bool:
+ for _ln, _raw, ts, cp in self.conds:
+ if ts.upper() == '%{HTTPS}' and cp.lower() in ('off', '!on', '!=on'):
+ return True
+ if ts.upper() == '%{SERVER_PORT}' and cp in ('80', '^80$'):
+ return True
+ return False
+
+ def _host_conds_only(self) -> bool:
+ return bool(self.conds) and all(
+ ts.upper() == '%{HTTP_HOST}' for _ln, _raw, ts, _cp in self.conds)
+
+ def _handle_rewrite_rule(self, lineno: int, raw: str, parts: List[str]) -> None:
+ if len(parts) < 3:
+ self.flag(lineno, raw, 'malformed RewriteRule (expected pattern and substitution)')
+ self.conds = []
+ return
+ pattern, subst = parts[1], parts[2]
+ flags = _parse_flags(parts[3]) if len(parts) > 3 else []
+ upper_flags = [f.upper() for f in flags]
+
+ redirect_status = None
+ for f in upper_flags:
+ if f == 'R':
+ redirect_status = 302
+ elif f.startswith('R='):
+ try:
+ redirect_status = int(f[2:])
+ except ValueError:
+ redirect_status = 302
+
+ # --- condition-driven patterns (detected as a unit) ---------------
+ if self.conds:
+ fc_target = self._front_controller(subst)
+ if fc_target is not None:
+ self.emit([f'try_files $uri $uri/ {fc_target};'],
+ source='front-controller block (RewriteCond !-f/!-d + RewriteRule)',
+ lineno=lineno)
+ self.note('Detected the standard front-controller block '
+ '(WordPress/Laravel-style) and converted it to try_files.')
+ self.conds = []
+ return
+
+ if self._https_off_cond() and redirect_status:
+ buf = self._target().buf
+ if buf:
+ buf.append('')
+ buf.append(f'# from: {raw} (line {lineno})')
+ buf.append('# NOTE: ServerKit manages HTTP->HTTPS redirects separately and')
+ buf.append('# HTTPS is optional — enable it in the site SSL settings instead.')
+ buf.append('# Equivalent left commented out on purpose:')
+ buf.append('# if ($scheme = http) {')
+ buf.append(f'# return {redirect_status if redirect_status in (301, 302) else 301} https://$host$request_uri;')
+ buf.append('# }')
+ self.note('An HTTPS-forcing redirect was found; ServerKit manages '
+ 'HTTP->HTTPS separately (HTTPS is optional), so the '
+ 'equivalent was emitted commented out.')
+ self.conds = []
+ return
+
+ if self._host_conds_only() and redirect_status:
+ if len(self.conds) == 1:
+ self._emit_host_redirect(lineno, raw, pattern, subst,
+ redirect_status)
+ else:
+ for c_ln, c_raw, _ts, _cp in self.conds:
+ self.flag(c_ln, c_raw,
+ 'multiple RewriteCond %{HTTP_HOST} conditions '
+ 'cannot be combined in a single nginx if')
+ self.flag(lineno, raw,
+ 'depends on multiple host conditions above')
+ self.conds = []
+ return
+
+ # Untranslatable condition set: flag conds + rule, drop nothing.
+ for c_ln, c_raw, ts, _cp in self.conds:
+ self.flag(c_ln, c_raw,
+ f'RewriteCond on {ts} cannot be translated automatically')
+ self.flag(lineno, raw,
+ 'skipped because its RewriteCond lines above could not be translated')
+ self.conds = []
+ return
+
+ # --- plain rules ---------------------------------------------------
+ pattern = _normalize_pattern(pattern)
+ if 'NC' in upper_flags:
+ pattern = '(?i)' + pattern
+ self.note('[NC] flags were converted to a (?i) case-insensitive '
+ 'regex prefix.')
+ subst = _normalize_subst(subst)
+
+ if 'QSA' in upper_flags:
+ if '?' in subst:
+ self.note('[QSA] with a query string in the substitution: nginx '
+ 'replaces the query string when "?" is present — append '
+ '&$args manually if the original args must be kept.')
+ else:
+ self.note('[QSA] is the nginx default: the original query string '
+ 'is appended automatically unless the target contains "?".')
+
+ if 'F' in upper_flags:
+ self.emit([f'location ~ {pattern} {{',
+ f'{_INDENT}return 403;', '}'],
+ source=raw, lineno=lineno)
+ return
+ if 'G' in upper_flags:
+ self.emit([f'location ~ {pattern} {{',
+ f'{_INDENT}return 410;', '}'],
+ source=raw, lineno=lineno)
+ return
+
+ if subst == '-':
+ self.flag(lineno, raw,
+ 'passthrough rule ("-" substitution) with no translatable '
+ 'flag has no effect in nginx')
+ return
+
+ if redirect_status:
+ status = redirect_status if redirect_status in (301, 302, 303, 307, 308) else 302
+ self.emit([f'location ~ {pattern} {{',
+ f'{_INDENT}return {status} {subst};', '}'],
+ source=raw, lineno=lineno)
+ self.note('External redirects were emitted as location + return; '
+ '$1..$9 backreferences come from the location regex.')
+ return
+
+ suffix = ' last' if 'L' in upper_flags else ''
+ if 'L' in upper_flags:
+ self.note('[L] flags map to the nginx rewrite "last" modifier '
+ '(stop processing and re-run location matching).')
+ self.emit([f'rewrite {pattern} {subst}{suffix};'],
+ source=raw, lineno=lineno)
+
+ def _emit_host_redirect(self, lineno: int, raw: str, pattern: str,
+ subst: str, status: int) -> None:
+ c_ln, c_raw, _ts, cp = self.conds[0]
+ negated = cp.startswith('!')
+ if negated:
+ cp = cp[1:]
+ # Literal host match: ^escaped\.host$ with no other regex metachars.
+ literal = None
+ m = re.fullmatch(r'\^([A-Za-z0-9\\.\-]+)\$', cp)
+ if m and not re.search(r'[\[\](){}|*+?]', m.group(1)):
+ literal = m.group(1).replace(r'\.', '.')
+ if literal is not None:
+ cond = f'$host {"!=" if negated else "="} {literal}'
+ else:
+ cond = f'$host {"!~*" if negated else "~*"} {cp}'
+
+ target = subst
+ if _is_catch_all(pattern):
+ if target.endswith('/$1'):
+ target = target[:-3] + '$request_uri'
+ elif target.endswith('$1'):
+ target = target[:-2] + '$request_uri'
+ if '%1' in target or re.search(r'%\d', target):
+ self.flag(c_ln, c_raw, 'RewriteCond backreferences (%N) are not supported')
+ self.flag(lineno, raw, 'uses RewriteCond backreferences (%N)')
+ return
+
+ status = status if status in (301, 302) else 301
+ self.emit([f'if ({cond}) {{',
+ f'{_INDENT}return {status} {target};', '}'],
+ source=f'{c_raw} + {raw}', lineno=lineno)
+ self.note('Host-based redirects were converted to an if ($host ...) '
+ 'block; a dedicated server block per hostname is cleaner if '
+ 'you control the full vhost.')
+
+ # -- simple directives ---------------------------------------------------
+
+ def _handle_redirect(self, lineno: int, raw: str, parts: List[str]) -> None:
+ word = parts[0].lower()
+ args = parts[1:]
+ status = 302
+ if word == 'redirectpermanent':
+ status = 301
+ elif word == 'redirecttemp':
+ status = 302
+ elif word == 'redirect' and args:
+ token = args[0].lower()
+ mapped = {'permanent': 301, 'temp': 302, 'seeother': 303,
+ 'gone': 410}.get(token)
+ if mapped is not None:
+ status = mapped
+ args = args[1:]
+ elif token.isdigit():
+ status = int(token)
+ args = args[1:]
+
+ if status == 410:
+ if not args:
+ self.flag(lineno, raw, 'Redirect gone requires a path')
+ return
+ path = args[0]
+ self.emit([f'location {path} {{', f'{_INDENT}return 410;', '}'],
+ source=raw, lineno=lineno)
+ return
+
+ if len(args) < 2:
+ self.flag(lineno, raw, 'malformed Redirect (expected path and target URL)')
+ return
+ path, url = args[0], args[1]
+ if not path.startswith('/'):
+ self.flag(lineno, raw, 'Redirect path must start with /')
+ return
+ if status == 301:
+ self.emit([f'rewrite ^{re.escape(path)}(/.*)?$ {url}$1 permanent;'],
+ source=raw, lineno=lineno)
+ elif status == 302:
+ self.emit([f'rewrite ^{re.escape(path)}(/.*)?$ {url}$1 redirect;'],
+ source=raw, lineno=lineno)
+ else:
+ self.emit([f'location = {path} {{',
+ f'{_INDENT}return {status} {url};', '}'],
+ source=raw, lineno=lineno)
+ self.note(f'Redirect with status {status}: nginx rewrite flags only '
+ 'support 301/302, so an exact-match location was used '
+ '(sub-paths are not carried over).')
+ self.note('Apache Redirect carries the request remainder onto the '
+ 'target; the emitted rewrite preserves that with $1.')
+
+ def _handle_redirect_match(self, lineno: int, raw: str, parts: List[str]) -> None:
+ args = parts[1:]
+ status = 302
+ if args and (args[0].isdigit() or args[0].lower() in ('permanent', 'temp', 'gone')):
+ token = args[0].lower()
+ status = {'permanent': 301, 'temp': 302, 'gone': 410}.get(
+ token, int(args[0]) if args[0].isdigit() else 302)
+ args = args[1:]
+ if status == 410:
+ if not args:
+ self.flag(lineno, raw, 'malformed RedirectMatch')
+ return
+ self.emit([f'location ~ {args[0]} {{', f'{_INDENT}return 410;', '}'],
+ source=raw, lineno=lineno)
+ return
+ if len(args) < 2:
+ self.flag(lineno, raw, 'malformed RedirectMatch (expected regex and target URL)')
+ return
+ regex, url = args[0], args[1]
+ status = status if status in (301, 302, 303, 307, 308) else 302
+ self.emit([f'location ~ {regex} {{',
+ f'{_INDENT}return {status} {url};', '}'],
+ source=raw, lineno=lineno)
+
+ def _handle_error_document(self, lineno: int, raw: str) -> None:
+ m = re.match(r'(?i)ErrorDocument\s+(\d{3})\s+(.+)$', raw)
+ if not m:
+ self.flag(lineno, raw, 'malformed ErrorDocument')
+ return
+ code, target = m.group(1), m.group(2).strip()
+ if target.startswith('"') or target.startswith("'"):
+ self.flag(lineno, raw,
+ 'ErrorDocument with an inline text message has no nginx '
+ 'equivalent; point it at an error page file instead')
+ return
+ self.emit([f'error_page {code} {target};'], source=raw, lineno=lineno)
+ if target.startswith(('http://', 'https://')):
+ self.note('error_page with an absolute URL makes nginx answer with '
+ 'a 302 redirect to it.')
+
+ def _handle_options(self, lineno: int, raw: str, parts: List[str]) -> None:
+ leftovers = []
+ for token in parts[1:]:
+ sign = '+'
+ name = token
+ if token[0] in '+-':
+ sign, name = token[0], token[1:]
+ lname = name.lower()
+ if lname == 'indexes':
+ self.emit([f'autoindex {"off" if sign == "-" else "on"};'],
+ source=raw, lineno=lineno)
+ elif lname in ('followsymlinks', 'symlinksifownermatch'):
+ self.note('Options FollowSymLinks has no nginx equivalent '
+ '(nginx follows symlinks by default) — omitted.')
+ elif lname == 'multiviews':
+ self.note('Options MultiViews (content negotiation) has no '
+ 'nginx equivalent — omitted; rewrites do not need it.')
+ elif lname == 'none':
+ self.emit(['autoindex off;'], source=raw, lineno=lineno)
+ else:
+ leftovers.append(token)
+ if leftovers:
+ self.flag(lineno, raw,
+ f'Options {" ".join(leftovers)} has no nginx equivalent')
+
+ def _handle_header(self, lineno: int, raw: str, parts: List[str]) -> None:
+ args = parts[1:]
+ if args and args[0].lower() in ('always', 'onsuccess'):
+ args = args[1:]
+ if not args:
+ self.flag(lineno, raw, 'malformed Header directive')
+ return
+ action = args[0].lower()
+ if action in ('unset', 'edit', 'edit*', 'echo', 'note'):
+ self.flag(lineno, raw,
+ f'Header {action} has no include-level nginx equivalent')
+ return
+ if action not in ('set', 'add', 'append', 'merge'):
+ self.flag(lineno, raw, f'unrecognized Header action "{args[0]}"')
+ return
+ if len(args) < 3:
+ self.flag(lineno, raw, 'malformed Header directive (missing value)')
+ return
+ name = args[1]
+ conditional = [a for a in args[3:] if a.lower().startswith(('env=', 'expr='))]
+ if conditional:
+ self.flag(lineno, raw,
+ 'conditional Header (env=/expr=) cannot be translated')
+ return
+ value = ' '.join(args[2:])
+ self.emit([f'add_header {name} "{value}" always;'],
+ source=raw, lineno=lineno)
+ self.note('mod_headers directives became add_header ... always; note '
+ 'that nginx add_header directives in a nested location '
+ 'replace (not merge with) inherited ones.')
+
+ # -- access control / auth ----------------------------------------------
+
+ def _handle_require(self, lineno: int, raw: str, parts: List[str]) -> None:
+ frame = self._target()
+ args = [a.lower() for a in parts[1:]]
+ if args[:2] == ['all', 'denied']:
+ frame.deny_all = True
+ elif args[:2] == ['all', 'granted']:
+ frame.allow_all = True
+ elif args[:1] == ['valid-user']:
+ frame.require_valid_user = True
+ elif args[:1] == ['user']:
+ frame.require_valid_user = True
+ self.note('Require user <name>: nginx basic auth accepts any user '
+ 'in the htpasswd file — keep only the intended users in it.')
+ elif args[:1] == ['ip']:
+ frame.allows.extend(parts[2:])
+ else:
+ self.flag(lineno, raw,
+ f'Require {" ".join(parts[1:])} has no nginx equivalent')
+
+ def _handle_allow_deny(self, lineno: int, raw: str, parts: List[str]) -> None:
+ frame = self._target()
+ word = parts[0].lower()
+ args = parts[1:]
+ if len(args) >= 2 and args[0].lower() == 'from':
+ args = args[1:]
+ if not args:
+ self.flag(lineno, raw, f'malformed {parts[0]} directive')
+ return
+ if word == 'deny':
+ if any(a.lower() == 'all' for a in args):
+ frame.deny_all = True
+ else:
+ frame.denies.extend(args)
+ else: # allow
+ if any(a.lower() == 'all' for a in args):
+ frame.allow_all = True
+ else:
+ frame.allows.extend(args)
+
+ def _flush_access_auth(self, frame: _Frame) -> None:
+ lines: List[str] = []
+ if frame.auth_basic or (frame.require_valid_user and frame.auth_userfile):
+ name = frame.auth_name or 'Restricted'
+ userfile = frame.auth_userfile or '/etc/nginx/.htpasswd'
+ lines.append(f'auth_basic "{name}";')
+ lines.append(f'auth_basic_user_file {userfile};')
+ if not frame.auth_userfile:
+ self.note('No AuthUserFile found — a placeholder htpasswd path '
+ 'was used; adjust it.')
+ self.note('Basic auth: upload the htpasswd file to the server and '
+ 'make sure auth_basic_user_file points at its real path.')
+ elif frame.require_valid_user:
+ self.note('Require valid-user was found without a usable AuthType '
+ 'Basic + AuthUserFile pair — basic auth was not emitted.')
+
+ for d in frame.denies:
+ lines.append(f'deny {d};')
+ if frame.allow_all and not frame.allows:
+ lines.append('allow all;')
+ for a in frame.allows:
+ lines.append(f'allow {a};')
+ if frame.allows and not frame.allow_all:
+ lines.append('deny all;')
+ self.note('Allow/Require ip entries are emitted before a final '
+ 'deny all; (nginx evaluates allow/deny in order).')
+ elif frame.deny_all:
+ lines.append('deny all;')
+
+ if lines:
+ if frame.buf:
+ frame.buf.append('')
+ frame.buf.append('# access control / auth (from Allow/Deny/Require/Auth* directives)')
+ frame.buf.extend(lines)
+
+ # -- block tags ------------------------------------------------------------
+
+ def _open_block(self, lineno: int, raw: str) -> bool:
+ m = re.match(r'<IfModule\s+(!?[\w./\-]+)\s*>$', raw, re.IGNORECASE)
+ if m:
+ self.stack.append(_Frame('ifmodule', tag='ifmodule',
+ line=lineno, raw=raw))
+ self.note(f'<IfModule {m.group(1)}> wrapper removed — its contents '
+ 'were processed directly.')
+ return True
+ m = re.match(r'<Files\s+"?(.+?)"?\s*>$', raw, re.IGNORECASE)
+ if m and not raw.lower().startswith('<filesmatch'):
+ regex = _wildcard_to_regex(m.group(1))
+ frame = _Frame('files', tag='files',
+ location=f'~ /{regex}$', line=lineno, raw=raw)
+ self.stack.append(frame)
+ return True
+ m = re.match(r'<FilesMatch\s+"?(.+?)"?\s*>$', raw, re.IGNORECASE)
+ if m:
+ frame = _Frame('files', tag='filesmatch',
+ location=f'~ {m.group(1)}', line=lineno, raw=raw)
+ self.stack.append(frame)
+ return True
+ m = re.match(r'<(\w+)[^>]*>$', raw)
+ if m:
+ self.stack.append(_Frame('opaque', tag=m.group(1).lower(),
+ line=lineno, raw=raw))
+ self.flag(lineno, raw,
+ f'<{m.group(1)}> blocks are not translated; their '
+ 'contents were still scanned individually')
+ return True
+ return False
+
+ def _close_block(self, lineno: int, raw: str) -> bool:
+ m = re.match(r'</(\w+)\s*>$', raw)
+ if not m:
+ return False
+ tag = m.group(1).lower()
+ # Find the matching open frame (tolerate mismatched close tags).
+ idx = None
+ for i in range(len(self.stack) - 1, 0, -1):
+ f = self.stack[i]
+ if f.tag == tag or (tag == 'ifmodule' and f.kind == 'ifmodule') or \
+ (tag in ('files', 'filesmatch') and f.kind == 'files'):
+ idx = i
+ break
+ if idx is None:
+ self.flag(lineno, raw, f'unmatched closing tag </{tag}>')
+ return True
+ frame = self.stack.pop(idx)
+ if frame.kind == 'files':
+ self._flush_access_auth(frame)
+ parent = self._target()
+ if frame.buf:
+ if parent.buf:
+ parent.buf.append('')
+ parent.buf.append(f'# from: {frame.raw} (line {frame.line})')
+ parent.buf.append(f'location {frame.location} {{')
+ parent.buf.extend(
+ _INDENT + l if l else '' for l in frame.buf)
+ parent.buf.append('}')
+ self.note('<Files>/<FilesMatch> wrappers became location '
+ 'regex blocks; Apache matches file names anywhere '
+ 'on disk while nginx matches the request URI — '
+ 'review nested paths.')
+ return True
+
+ # -- main loop ----------------------------------------------------------
+
+ def feed(self, lineno: int, raw: str) -> None:
+ line = raw.strip()
+ if not line or line.startswith('#'):
+ return
+
+ if line.startswith('</'):
+ if self._close_block(lineno, line):
+ return
+ if line.startswith('<'):
+ if self._open_block(lineno, line):
+ return
+ self.flag(lineno, line, 'unrecognized configuration block')
+ return
+
+ parts = _split(line)
+ if not parts:
+ return
+ word = parts[0].lower()
+
+ if word != 'rewritecond' and word != 'rewriterule' and self.conds:
+ # Conditions only apply to the next RewriteRule.
+ self._flush_dangling_conds()
+
+ if word == 'rewriteengine':
+ self.note('RewriteEngine directives were dropped (implicit in nginx).')
+ elif word == 'rewritebase':
+ base = parts[1] if len(parts) > 1 else '/'
+ self.note(f'RewriteBase {base} was dropped — nginx rewrites always '
+ 'work on the full URI; verify the emitted paths include '
+ 'the base prefix if the site lives in a subdirectory.')
+ elif word == 'rewriteoptions':
+ self.flag(lineno, line, 'RewriteOptions has no nginx equivalent')
+ elif word == 'rewritecond':
+ self._handle_rewrite_cond(lineno, line, parts)
+ elif word == 'rewriterule':
+ self._handle_rewrite_rule(lineno, line, parts)
+ elif word in ('redirect', 'redirectpermanent', 'redirecttemp'):
+ self._handle_redirect(lineno, line, parts)
+ elif word == 'redirectmatch':
+ self._handle_redirect_match(lineno, line, parts)
+ elif word == 'errordocument':
+ self._handle_error_document(lineno, line)
+ elif word == 'options':
+ self._handle_options(lineno, line, parts)
+ elif word == 'directoryindex':
+ if len(parts) > 1:
+ self.emit([f'index {" ".join(parts[1:])};'],
+ source=line, lineno=lineno)
+ else:
+ self.flag(lineno, line, 'malformed DirectoryIndex')
+ elif word == 'adddefaultcharset':
+ if len(parts) > 1 and parts[1].lower() != 'off':
+ self.emit([f'charset {parts[1]};'], source=line, lineno=lineno)
+ elif word == 'header':
+ self._handle_header(lineno, line, parts)
+ elif word == 'authtype':
+ if len(parts) > 1 and parts[1].lower() == 'basic':
+ self._target().auth_basic = True
+ else:
+ self.flag(lineno, line,
+ f'AuthType {parts[1] if len(parts) > 1 else "?"} is '
+ 'not supported (only Basic maps to nginx auth_basic)')
+ elif word == 'authname':
+ self._target().auth_name = ' '.join(parts[1:]) if len(parts) > 1 else None
+ elif word == 'authuserfile':
+ self._target().auth_userfile = parts[1] if len(parts) > 1 else None
+ elif word == 'require':
+ if len(parts) < 2:
+ self.flag(lineno, line, 'malformed Require directive')
+ else:
+ self._handle_require(lineno, line, parts)
+ elif word in ('allow', 'deny'):
+ self._handle_allow_deny(lineno, line, parts)
+ elif word == 'order':
+ self.note('Order directives were dropped; the emitted allow/deny '
+ 'lines already encode the effective policy in nginx order.')
+ elif word in _KNOWN_UNSUPPORTED:
+ self.flag(lineno, line, _KNOWN_UNSUPPORTED[word])
+ else:
+ self.flag(lineno, line,
+ 'unrecognized directive — no nginx equivalent known')
+
+ def finish(self) -> Dict:
+ self._flush_dangling_conds()
+ # Close any unclosed <Files>/<FilesMatch> blocks gracefully.
+ while len(self.stack) > 1:
+ frame = self.stack[-1]
+ if frame.kind == 'files':
+ self._close_block(frame.line, f'</{frame.tag}>')
+ self.flag(frame.line, frame.raw,
+ 'block was never closed — treated as closed at EOF')
+ else:
+ self.stack.pop()
+ self._flush_access_auth(self.root)
+
+ nginx = '\n'.join(self.root.buf).strip('\n')
+ if nginx:
+ nginx += '\n'
+ return {
+ 'nginx': nginx,
+ 'notes': self.notes,
+ 'unsupported': self.unsupported,
+ }
+
+
+def convert(htaccess_text: str) -> Dict:
+ """Convert ``.htaccess`` text to nginx directives.
+
+ Returns ``{'nginx': str, 'notes': [str], 'unsupported': [dict]}``.
+ Raises ``ValueError`` if the input exceeds :data:`MAX_INPUT_BYTES`.
+ """
+ if htaccess_text is None:
+ htaccess_text = ''
+ if not isinstance(htaccess_text, str):
+ raise ValueError('htaccess_text must be a string')
+ if len(htaccess_text.encode('utf-8', errors='replace')) > MAX_INPUT_BYTES:
+ raise ValueError('.htaccess input exceeds the 256KB limit')
+
+ conv = _Converter()
+ # Handle Apache line continuations (trailing backslash).
+ logical: List[tuple] = []
+ pending = ''
+ pending_line = 0
+ for i, raw in enumerate(htaccess_text.splitlines(), start=1):
+ if pending:
+ merged = pending + ' ' + raw.strip()
+ else:
+ merged = raw
+ pending_line = i
+ if merged.rstrip().endswith('\\'):
+ pending = merged.rstrip()[:-1].rstrip()
+ continue
+ logical.append((pending_line, merged))
+ pending = ''
+ if pending:
+ logical.append((pending_line, pending))
+
+ for lineno, line in logical:
+ conv.feed(lineno, line)
+ return conv.finish()
diff --git a/backend/tests/test_htaccess_converter.py b/backend/tests/test_htaccess_converter.py
new file mode 100644
index 00000000..980c4992
--- /dev/null
+++ b/backend/tests/test_htaccess_converter.py
@@ -0,0 +1,585 @@
+"""Tests for the .htaccess -> nginx converter (service + API endpoint)."""
+import re
+
+import pytest
+
+from app.services.htaccess_converter import MAX_INPUT_BYTES, convert
+
+
+def _nginx(text):
+ return convert(text)['nginx']
+
+
+def _unsupported(text):
+ return convert(text)['unsupported']
+
+
+# ---------------------------------------------------------------------------
+# Redirect family
+# ---------------------------------------------------------------------------
+class TestRedirects:
+ def test_redirect_301(self):
+ out = _nginx('Redirect 301 /old https://example.com/new')
+ assert 'rewrite ^/old(/.*)?$ https://example.com/new$1 permanent;' in out
+
+ def test_redirect_default_status_is_302(self):
+ out = _nginx('Redirect /old https://example.com/new')
+ assert 'redirect;' in out
+ assert 'permanent;' not in out
+
+ def test_redirect_permanent_keyword(self):
+ out = _nginx('Redirect permanent /a https://x.test/b')
+ assert 'permanent;' in out
+
+ def test_redirect_permanent_directive(self):
+ out = _nginx('RedirectPermanent /a https://x.test/b')
+ assert 'permanent;' in out
+
+ def test_redirect_temp_directive(self):
+ out = _nginx('RedirectTemp /a https://x.test/b')
+ assert 'redirect;' in out
+
+ def test_redirect_gone(self):
+ out = _nginx('Redirect gone /dead')
+ assert 'location /dead {' in out
+ assert 'return 410;' in out
+
+ def test_redirect_odd_status_uses_location(self):
+ out = _nginx('Redirect 303 /a https://x.test/b')
+ assert 'location = /a {' in out
+ assert 'return 303 https://x.test/b;' in out
+
+ def test_redirect_match(self):
+ out = _nginx(r'RedirectMatch 301 ^/blog/(\d+)$ https://x.test/posts/$1')
+ assert r'location ~ ^/blog/(\d+)$ {' in out
+ assert 'return 301 https://x.test/posts/$1;' in out
+
+ def test_redirect_match_default_302(self):
+ out = _nginx('RedirectMatch ^/tmp/(.*)$ /elsewhere/$1')
+ assert 'return 302 /elsewhere/$1;' in out
+
+ def test_malformed_redirect_flagged(self):
+ unsup = _unsupported('Redirect 301 /only-path')
+ assert len(unsup) == 1
+ assert unsup[0]['line'] == 1
+
+
+# ---------------------------------------------------------------------------
+# RewriteRule
+# ---------------------------------------------------------------------------
+class TestRewriteRule:
+ def test_internal_rewrite(self):
+ out = _nginx('RewriteRule ^shop/(.*)$ /store/$1')
+ assert 'rewrite ^/shop/(.*)$ /store/$1;' in out
+
+ def test_leading_slash_normalized(self):
+ out = _nginx('RewriteRule ^foo$ /bar')
+ assert '^/foo$' in out
+
+ def test_l_flag_becomes_last(self):
+ res = convert('RewriteRule ^a$ /b [L]')
+ assert 'rewrite ^/a$ /b last;' in res['nginx']
+ assert any('[L]' in n for n in res['notes'])
+
+ def test_nc_flag_becomes_case_insensitive_prefix(self):
+ res = convert('RewriteRule ^Docs/(.*)$ /documents/$1 [NC]')
+ assert 'rewrite (?i)^/Docs/(.*)$ /documents/$1;' in res['nginx']
+ assert any('(?i)' in n for n in res['notes'])
+
+ def test_r301_becomes_location_return(self):
+ out = _nginx('RewriteRule ^old-page$ /new-page [R=301,L]')
+ assert 'location ~ ^/old-page$ {' in out
+ assert 'return 301 /new-page;' in out
+
+ def test_r_flag_alone_is_302(self):
+ out = _nginx('RewriteRule ^x$ /y [R]')
+ assert 'return 302 /y;' in out
+
+ def test_backrefs_preserved_in_redirect(self):
+ out = _nginx('RewriteRule ^cat/(.*)$ https://x.test/category/$1 [R=301]')
+ assert 'return 301 https://x.test/category/$1;' in out
+
+ def test_qsa_noted(self):
+ res = convert('RewriteRule ^p/(.*)$ /page.php?id=$1 [QSA,L]')
+ assert any('QSA' in n for n in res['notes'])
+
+ def test_qsa_without_query_noted_as_default(self):
+ res = convert('RewriteRule ^a/(.*)$ /b/$1 [QSA]')
+ assert any('nginx default' in n for n in res['notes'])
+
+ def test_relative_substitution_gets_slash(self):
+ out = _nginx('RewriteRule ^a$ b.html')
+ assert 'rewrite ^/a$ /b.html;' in out
+
+ def test_forbidden_flag(self):
+ out = _nginx('RewriteRule ^secret - [F]')
+ assert 'return 403;' in out
+
+ def test_gone_flag(self):
+ out = _nginx('RewriteRule ^dead$ - [G]')
+ assert 'return 410;' in out
+
+ def test_passthrough_dash_flagged(self):
+ unsup = _unsupported('RewriteRule ^keep$ - [L]')
+ assert len(unsup) == 1
+ assert 'passthrough' in unsup[0]['reason']
+
+ def test_rewrite_engine_dropped_with_note(self):
+ res = convert('RewriteEngine On\nRewriteRule ^a$ /b')
+ assert 'RewriteEngine' not in res['nginx']
+ assert res['unsupported'] == []
+ assert any('RewriteEngine' in n for n in res['notes'])
+
+ def test_rewrite_base_noted(self):
+ res = convert('RewriteBase /subdir/')
+ assert any('RewriteBase /subdir/' in n for n in res['notes'])
+
+ def test_from_comment_present(self):
+ out = _nginx('RewriteRule ^a$ /b [L]')
+ assert '# from: RewriteRule ^a$ /b [L] (line 1)' in out
+
+
+# ---------------------------------------------------------------------------
+# Front controller (WP / Laravel) detection
+# ---------------------------------------------------------------------------
+class TestFrontController:
+ WP = (
+ '<IfModule mod_rewrite.c>\n'
+ 'RewriteEngine On\n'
+ 'RewriteBase /\n'
+ 'RewriteRule ^index\\.php$ - [L]\n'
+ 'RewriteCond %{REQUEST_FILENAME} !-f\n'
+ 'RewriteCond %{REQUEST_FILENAME} !-d\n'
+ 'RewriteRule . /index.php [L]\n'
+ '</IfModule>\n'
+ )
+
+ def test_wordpress_block_becomes_try_files(self):
+ res = convert(self.WP)
+ assert 'try_files $uri $uri/ /index.php?$args;' in res['nginx']
+ assert any('front-controller' in n for n in res['notes'])
+
+ def test_laravel_block(self):
+ text = (
+ 'RewriteCond %{REQUEST_FILENAME} !-d\n'
+ 'RewriteCond %{REQUEST_FILENAME} !-f\n'
+ 'RewriteRule ^ index.php [L]\n'
+ )
+ assert 'try_files $uri $uri/ /index.php?$args;' in _nginx(text)
+
+ def test_html_front_controller_no_args(self):
+ text = (
+ 'RewriteCond %{REQUEST_FILENAME} !-f\n'
+ 'RewriteCond %{REQUEST_FILENAME} !-d\n'
+ 'RewriteRule . /index.html [L]\n'
+ )
+ assert 'try_files $uri $uri/ /index.html;' in _nginx(text)
+
+ def test_extra_symlink_cond_still_detected(self):
+ text = (
+ 'RewriteCond %{REQUEST_FILENAME} !-f\n'
+ 'RewriteCond %{REQUEST_FILENAME} !-d\n'
+ 'RewriteCond %{REQUEST_FILENAME} !-l\n'
+ 'RewriteRule ^(.*)$ index.php [L]\n'
+ )
+ assert 'try_files' in _nginx(text)
+
+ def test_only_f_cond_not_detected_as_front_controller(self):
+ text = (
+ 'RewriteCond %{REQUEST_FILENAME} !-f\n'
+ 'RewriteRule . /index.php [L]\n'
+ )
+ res = convert(text)
+ assert 'try_files' not in res['nginx']
+ # Both cond and rule flagged, nothing silently dropped.
+ assert len(res['unsupported']) == 2
+
+
+# ---------------------------------------------------------------------------
+# RewriteCond host / https handling
+# ---------------------------------------------------------------------------
+class TestCondRedirects:
+ def test_host_redirect_literal(self):
+ text = (
+ 'RewriteCond %{HTTP_HOST} ^example\\.com$\n'
+ 'RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]\n'
+ )
+ res = convert(text)
+ assert 'if ($host = example.com) {' in res['nginx']
+ assert 'return 301 https://www.example.com$request_uri;' in res['nginx']
+ assert any('dedicated server block' in n for n in res['notes'])
+
+ def test_host_redirect_negated_regex(self):
+ text = (
+ 'RewriteCond %{HTTP_HOST} !^www\\.\n'
+ 'RewriteRule ^(.*)$ https://www.example.com/$1 [R=301]\n'
+ )
+ out = _nginx(text)
+ assert 'if ($host !~* ^www\\.) {' in out
+
+ def test_https_off_redirect_is_commented(self):
+ text = (
+ 'RewriteCond %{HTTPS} off\n'
+ 'RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]\n'
+ )
+ res = convert(text)
+ # Emitted, but only as comments — HTTPS is optional in ServerKit.
+ assert '# if ($scheme = http) {' in res['nginx']
+ for line in res['nginx'].splitlines():
+ if 'return 301 https://$host$request_uri' in line:
+ assert line.lstrip().startswith('#')
+ assert any('HTTPS is optional' in n or 'HTTP->HTTPS' in n
+ for n in res['notes'])
+
+ def test_untranslatable_cond_flags_cond_and_rule(self):
+ text = (
+ 'RewriteCond %{REQUEST_URI} !^/admin\n'
+ 'RewriteRule ^(.*)$ /public/$1 [L]\n'
+ )
+ unsup = _unsupported(text)
+ assert len(unsup) == 2
+ assert unsup[0]['line'] == 1
+ assert unsup[1]['line'] == 2
+
+ def test_dangling_cond_flagged(self):
+ unsup = _unsupported('RewriteCond %{HTTP_HOST} ^x$')
+ assert len(unsup) == 1
+ assert 'without a following RewriteRule' in unsup[0]['reason']
+
+
+# ---------------------------------------------------------------------------
+# Simple directives
+# ---------------------------------------------------------------------------
+class TestSimpleDirectives:
+ def test_error_document(self):
+ out = _nginx('ErrorDocument 404 /errors/404.html')
+ assert 'error_page 404 /errors/404.html;' in out
+
+ def test_error_document_url_noted(self):
+ res = convert('ErrorDocument 500 https://x.test/oops')
+ assert 'error_page 500 https://x.test/oops;' in res['nginx']
+ assert any('302' in n for n in res['notes'])
+
+ def test_error_document_text_message_flagged(self):
+ unsup = _unsupported('ErrorDocument 403 "Access denied"')
+ assert len(unsup) == 1
+ assert 'text message' in unsup[0]['reason']
+
+ def test_options_minus_indexes(self):
+ assert 'autoindex off;' in _nginx('Options -Indexes')
+
+ def test_options_plus_indexes(self):
+ assert 'autoindex on;' in _nginx('Options +Indexes')
+
+ def test_options_followsymlinks_noted_not_flagged(self):
+ res = convert('Options +FollowSymLinks')
+ assert res['unsupported'] == []
+ assert any('FollowSymLinks' in n for n in res['notes'])
+
+ def test_options_unknown_token_flagged(self):
+ unsup = _unsupported('Options +ExecCGI')
+ assert len(unsup) == 1
+ assert 'ExecCGI' in unsup[0]['reason']
+
+ def test_directory_index(self):
+ out = _nginx('DirectoryIndex index.php index.html')
+ assert 'index index.php index.html;' in out
+
+ def test_add_default_charset(self):
+ assert 'charset UTF-8;' in _nginx('AddDefaultCharset UTF-8')
+
+ def test_header_set(self):
+ res = convert('Header set X-Frame-Options "SAMEORIGIN"')
+ assert 'add_header X-Frame-Options "SAMEORIGIN" always;' in res['nginx']
+ assert any('add_header' in n for n in res['notes'])
+
+ def test_header_always_set(self):
+ out = _nginx('Header always set X-Content-Type-Options "nosniff"')
+ assert 'add_header X-Content-Type-Options "nosniff" always;' in out
+
+ def test_header_unset_flagged(self):
+ unsup = _unsupported('Header unset X-Powered-By')
+ assert len(unsup) == 1
+
+ def test_header_env_conditional_flagged(self):
+ unsup = _unsupported('Header set X-Foo "bar" env=HTTPS')
+ assert len(unsup) == 1
+ assert 'env=' in unsup[0]['reason'] or 'conditional' in unsup[0]['reason']
+
+
+# ---------------------------------------------------------------------------
+# Access control + basic auth
+# ---------------------------------------------------------------------------
+class TestAccessAndAuth:
+ def test_deny_from_all(self):
+ assert 'deny all;' in _nginx('Deny from all')
+
+ def test_require_all_denied(self):
+ assert 'deny all;' in _nginx('Require all denied')
+
+ def test_require_all_granted(self):
+ assert 'allow all;' in _nginx('Require all granted')
+
+ def test_allow_from_ip_gets_deny_all(self):
+ out = _nginx('Order deny,allow\nDeny from all\nAllow from 10.0.0.1')
+ allow_idx = out.index('allow 10.0.0.1;')
+ deny_idx = out.index('deny all;')
+ assert allow_idx < deny_idx
+
+ def test_require_ip(self):
+ out = _nginx('Require ip 192.168.1.0/24')
+ assert 'allow 192.168.1.0/24;' in out
+ assert 'deny all;' in out
+
+ def test_deny_specific_ip(self):
+ out = _nginx('Deny from 1.2.3.4')
+ assert 'deny 1.2.3.4;' in out
+ assert 'deny all;' not in out
+
+ def test_basic_auth_block(self):
+ text = (
+ 'AuthType Basic\n'
+ 'AuthName "Members Only"\n'
+ 'AuthUserFile /home/site/.htpasswd\n'
+ 'Require valid-user\n'
+ )
+ res = convert(text)
+ assert 'auth_basic "Members Only";' in res['nginx']
+ assert 'auth_basic_user_file /home/site/.htpasswd;' in res['nginx']
+ assert any('htpasswd' in n for n in res['notes'])
+
+ def test_basic_auth_without_userfile_uses_placeholder(self):
+ res = convert('AuthType Basic\nRequire valid-user\n')
+ assert 'auth_basic_user_file /etc/nginx/.htpasswd;' in res['nginx']
+ assert any('placeholder' in n for n in res['notes'])
+
+ def test_digest_auth_flagged(self):
+ unsup = _unsupported('AuthType Digest')
+ assert len(unsup) == 1
+
+ def test_require_valid_user_alone_noted(self):
+ res = convert('Require valid-user')
+ assert 'auth_basic' not in res['nginx']
+ assert any('without a usable AuthType' in n for n in res['notes'])
+
+
+# ---------------------------------------------------------------------------
+# <Files> / <FilesMatch> / <IfModule> wrappers
+# ---------------------------------------------------------------------------
+class TestWrappers:
+ def test_files_block_becomes_location(self):
+ text = '<Files "wp-config.php">\nRequire all denied\n</Files>'
+ out = _nginx(text)
+ assert re.search(r'location ~ /wp\\?-config\\\.php\$ \{', out)
+ assert 'deny all;' in out
+
+ def test_filesmatch_block(self):
+ text = '<FilesMatch "\\.(env|log)$">\nDeny from all\n</FilesMatch>'
+ out = _nginx(text)
+ assert 'location ~ \\.(env|log)$ {' in out
+ assert 'deny all;' in out
+
+ def test_files_wildcard(self):
+ text = '<Files "*.bak">\nRequire all denied\n</Files>'
+ out = _nginx(text)
+ assert 'location ~ /.*\\.bak$ {' in out
+
+ def test_unsupported_directive_inside_files_flagged(self):
+ text = '<Files "x.php">\nphp_value memory_limit 256M\n</Files>'
+ res = convert(text)
+ assert len(res['unsupported']) == 1
+ assert res['unsupported'][0]['line'] == 2
+
+ def test_unclosed_files_block_flagged_but_flushed(self):
+ text = '<Files "secret.txt">\nDeny from all\n'
+ res = convert(text)
+ assert 'deny all;' in res['nginx']
+ assert any('never closed' in u['reason'] for u in res['unsupported'])
+
+ def test_ifmodule_unwrapped_with_note(self):
+ text = '<IfModule mod_rewrite.c>\nRewriteRule ^a$ /b\n</IfModule>'
+ res = convert(text)
+ assert 'rewrite ^/a$ /b;' in res['nginx']
+ assert res['unsupported'] == []
+ assert any('IfModule' in n and 'removed' in n for n in res['notes'])
+
+ def test_nested_ifmodule_in_files(self):
+ text = (
+ '<Files "a.txt">\n'
+ '<IfModule mod_authz_core.c>\n'
+ 'Require all denied\n'
+ '</IfModule>\n'
+ '</Files>\n'
+ )
+ out = _nginx(text)
+ assert 'deny all;' in out
+
+ def test_unknown_block_flagged_contents_scanned(self):
+ text = '<Limit GET POST>\nDeny from all\n</Limit>'
+ res = convert(text)
+ assert any('<Limit' in u['directive'] for u in res['unsupported'])
+ # Contents still scanned, not silently dropped.
+ assert 'deny all;' in res['nginx']
+
+
+# ---------------------------------------------------------------------------
+# Unsupported directives (never silently dropped)
+# ---------------------------------------------------------------------------
+class TestUnsupported:
+ def test_mod_deflate_flagged_with_reason(self):
+ unsup = _unsupported('AddOutputFilterByType DEFLATE text/html')
+ assert len(unsup) == 1
+ assert 'gzip' in unsup[0]['reason']
+
+ def test_mod_expires_flagged(self):
+ unsup = _unsupported('ExpiresByType image/png "access plus 1 month"')
+ assert 'expires' in unsup[0]['reason']
+
+ def test_php_value_flagged(self):
+ unsup = _unsupported('php_value upload_max_filesize 64M')
+ assert 'PHP-FPM' in unsup[0]['reason']
+
+ def test_setenv_flagged(self):
+ unsup = _unsupported('SetEnv APP_ENV production')
+ assert len(unsup) == 1
+
+ def test_unknown_directive_flagged(self):
+ unsup = _unsupported('FancyIndexing on')
+ assert len(unsup) == 1
+ assert 'unrecognized' in unsup[0]['reason']
+
+ def test_line_numbers_accurate(self):
+ text = 'Options -Indexes\n\n# comment\nphp_flag display_errors off\nSetEnv X 1\n'
+ unsup = _unsupported(text)
+ assert [u['line'] for u in unsup] == [4, 5]
+
+ def test_directive_text_included(self):
+ unsup = _unsupported('SetEnv FOO bar')
+ assert unsup[0]['directive'] == 'SetEnv FOO bar'
+
+
+# ---------------------------------------------------------------------------
+# Robustness
+# ---------------------------------------------------------------------------
+class TestRobustness:
+ def test_empty_input(self):
+ res = convert('')
+ assert res == {'nginx': '', 'notes': [], 'unsupported': []}
+
+ def test_none_input(self):
+ res = convert(None)
+ assert res['nginx'] == ''
+
+ def test_whitespace_and_comments_only(self):
+ res = convert('# just a comment\n\n \n# another\n')
+ assert res['nginx'] == ''
+ assert res['unsupported'] == []
+
+ def test_garbage_input_safe(self):
+ res = convert('!!! not apache at all ~~~\x00\nRewriteRule ^a$ /b\n')
+ assert 'rewrite ^/a$ /b;' in res['nginx']
+ assert len(res['unsupported']) == 1
+
+ def test_line_continuations_merged(self):
+ text = 'Header set X-Long \\\n"value"\n'
+ assert 'add_header X-Long "value" always;' in _nginx(text)
+
+ def test_no_server_wrapper_ever_emitted(self):
+ text = (
+ 'RewriteEngine On\n'
+ 'Redirect 301 /a https://x.test/b\n'
+ 'ErrorDocument 404 /404.html\n'
+ 'Options -Indexes\n'
+ )
+ out = _nginx(text)
+ assert 'server {' not in out
+ assert 'http {' not in out
+
+ def test_over_256kb_raises(self):
+ big = 'Options -Indexes\n' * (MAX_INPUT_BYTES // 10)
+ assert len(big.encode()) > MAX_INPUT_BYTES
+ with pytest.raises(ValueError):
+ convert(big)
+
+ def test_exactly_at_cap_ok(self):
+ pad = '#' + 'x' * (MAX_INPUT_BYTES - 2) + '\n'
+ assert len(pad.encode()) == MAX_INPUT_BYTES
+ res = convert(pad)
+ assert res['nginx'] == ''
+
+ def test_non_string_raises(self):
+ with pytest.raises(ValueError):
+ convert(12345)
+
+ def test_kitchen_sink_ordering_stable(self):
+ text = (
+ 'Options -Indexes\n'
+ 'DirectoryIndex index.php\n'
+ 'ErrorDocument 404 /404.html\n'
+ '<Files ".htpasswd">\n'
+ 'Require all denied\n'
+ '</Files>\n'
+ )
+ out = _nginx(text)
+ assert out.index('autoindex off;') < out.index('index index.php;')
+ assert out.index('index index.php;') < out.index('error_page 404 /404.html;')
+ assert 'location ~' in out
+
+
+# ---------------------------------------------------------------------------
+# API endpoint
+# ---------------------------------------------------------------------------
+def _ensure_bp(app):
+ """Register the blueprint name-guarded (wiring into app/__init__.py is
+ owned by another change; the endpoint contract is tested here)."""
+ if 'htaccess_tools' not in app.blueprints:
+ from app.api.htaccess_tools import htaccess_tools_bp
+ app.register_blueprint(htaccess_tools_bp, url_prefix='/api/v1/apps')
+
+
+class TestApi:
+ def test_requires_auth(self, app, client):
+ _ensure_bp(app)
+ resp = client.post('/api/v1/apps/htaccess-convert',
+ json={'htaccess': 'Options -Indexes'})
+ assert resp.status_code == 401
+
+ def test_happy_path(self, app, client, auth_headers):
+ _ensure_bp(app)
+ resp = client.post(
+ '/api/v1/apps/htaccess-convert',
+ json={'htaccess': 'Options -Indexes\nSetEnv FOO bar\n'},
+ headers=auth_headers)
+ assert resp.status_code == 200
+ data = resp.get_json()
+ assert 'autoindex off;' in data['nginx']
+ assert isinstance(data['notes'], list)
+ assert len(data['unsupported']) == 1
+ assert data['unsupported'][0]['line'] == 2
+
+ def test_missing_body_400(self, app, client, auth_headers):
+ _ensure_bp(app)
+ resp = client.post('/api/v1/apps/htaccess-convert', json={},
+ headers=auth_headers)
+ assert resp.status_code == 400
+ assert 'error' in resp.get_json()
+
+ def test_blank_text_400(self, app, client, auth_headers):
+ _ensure_bp(app)
+ resp = client.post('/api/v1/apps/htaccess-convert',
+ json={'htaccess': ' '}, headers=auth_headers)
+ assert resp.status_code == 400
+
+ def test_non_string_400(self, app, client, auth_headers):
+ _ensure_bp(app)
+ resp = client.post('/api/v1/apps/htaccess-convert',
+ json={'htaccess': 42}, headers=auth_headers)
+ assert resp.status_code == 400
+
+ def test_oversize_413(self, app, client, auth_headers):
+ _ensure_bp(app)
+ big = 'Options -Indexes\n' * (MAX_INPUT_BYTES // 10)
+ resp = client.post('/api/v1/apps/htaccess-convert',
+ json={'htaccess': big}, headers=auth_headers)
+ assert resp.status_code == 413
+ assert 'error' in resp.get_json()
diff --git a/frontend/src/components/apps/HtaccessConverter.jsx b/frontend/src/components/apps/HtaccessConverter.jsx
new file mode 100644
index 00000000..79265624
--- /dev/null
+++ b/frontend/src/components/apps/HtaccessConverter.jsx
@@ -0,0 +1,177 @@
+import { useState } from 'react';
+import { FileCode2, ArrowRight, AlertTriangle } from 'lucide-react';
+import Modal from '@/components/Modal';
+import { Button } from '@/components/ui/button';
+import { Textarea } from '@/components/ui/textarea';
+import { CopyButton } from '@/components/CopyButton';
+import api from '../../services/api';
+import { useToast } from '../../contexts/ToastContext';
+
+// Paste-in .htaccess -> nginx converter for the per-site custom nginx rules
+// editor. Pairs with the site-import feature: imported cPanel sites carry
+// .htaccess files whose rewrite/redirect/auth rules need nginx equivalents.
+//
+// Usage (next to the custom-rules textarea):
+// <HtaccessConverter onInsert={(nginx) => setRules(r => (r ? r + '\n' : '') + nginx)} />
+//
+// `onInsert(nginxText)` is optional; without it the modal still offers
+// copy-to-clipboard. `trigger` overrides the default launcher button.
+export default function HtaccessConverter({ onInsert, trigger = null }) {
+ const toast = useToast();
+ const [open, setOpen] = useState(false);
+ const [source, setSource] = useState('');
+ const [converting, setConverting] = useState(false);
+ const [result, setResult] = useState(null);
+
+ const handleConvert = async () => {
+ if (!source.trim() || converting) return;
+ setConverting(true);
+ try {
+ const res = await api.convertHtaccess(source);
+ setResult(res);
+ if (!res.nginx && !(res.unsupported || []).length) {
+ toast.info('Nothing to convert — no directives found.');
+ }
+ } catch (err) {
+ toast.error(err.message || 'Conversion failed');
+ } finally {
+ setConverting(false);
+ }
+ };
+
+ const handleInsert = () => {
+ if (!result?.nginx) return;
+ onInsert?.(result.nginx);
+ toast.success('Converted rules inserted — review before saving.');
+ handleClose();
+ };
+
+ const handleClose = () => {
+ setOpen(false);
+ setResult(null);
+ setSource('');
+ };
+
+ const unsupported = result?.unsupported || [];
+ const notes = result?.notes || [];
+
+ return (
+ <>
+ {trigger ? (
+ <span onClick={() => setOpen(true)}>{trigger}</span>
+ ) : (
+ <Button type="button" variant="outline" size="sm" onClick={() => setOpen(true)}>
+ <FileCode2 size={16} />
+ Convert .htaccess
+ </Button>
+ )}
+
+ <Modal
+ open={open}
+ onClose={handleClose}
+ title="Convert .htaccess to nginx"
+ size="lg"
+ footer={(
+ <div className="htaccess-converter__footer">
+ <Button type="button" variant="ghost" onClick={handleClose}>
+ Close
+ </Button>
+ {result?.nginx && onInsert && (
+ <Button type="button" onClick={handleInsert}>
+ <ArrowRight size={16} />
+ Insert into rules
+ </Button>
+ )}
+ </div>
+ )}
+ >
+ <div className="htaccess-converter">
+ <p className="htaccess-converter__hint">
+ Paste the contents of an Apache <code>.htaccess</code> file
+ (e.g. from an imported cPanel site). Rewrites, redirects,
+ access rules and basic auth are translated to nginx
+ directives for the custom rules box; anything that has no
+ equivalent is listed below instead of being dropped.
+ </p>
+
+ <Textarea
+ className="htaccess-converter__input"
+ value={source}
+ onChange={(e) => setSource(e.target.value)}
+ placeholder={'RewriteEngine On\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]'}
+ rows={8}
+ spellCheck={false}
+ />
+
+ <div className="htaccess-converter__actions">
+ <Button
+ type="button"
+ onClick={handleConvert}
+ disabled={!source.trim() || converting}
+ >
+ {converting ? 'Converting…' : 'Convert'}
+ </Button>
+ </div>
+
+ {result && (
+ <div className="htaccess-converter__result">
+ <div className="htaccess-converter__pane">
+ <div className="htaccess-converter__pane-header">
+ <span>nginx directives</span>
+ {result.nginx && <CopyButton value={result.nginx} size="sm" variant="ghost" label="Copy nginx rules" />}
+ </div>
+ {result.nginx ? (
+ <pre className="htaccess-converter__output"><code>{result.nginx}</code></pre>
+ ) : (
+ <p className="htaccess-converter__empty">No translatable directives found.</p>
+ )}
+ </div>
+
+ {notes.length > 0 && (
+ <div className="htaccess-converter__pane">
+ <div className="htaccess-converter__pane-header">
+ <span>Notes</span>
+ </div>
+ <ul className="htaccess-converter__notes">
+ {notes.map((note) => (
+ <li key={note}>{note}</li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {unsupported.length > 0 && (
+ <div className="htaccess-converter__pane htaccess-converter__pane--warn">
+ <div className="htaccess-converter__pane-header">
+ <AlertTriangle size={15} />
+ <span>Not translated ({unsupported.length})</span>
+ </div>
+ <div className="htaccess-converter__table-wrap">
+ <table className="htaccess-converter__table">
+ <thead>
+ <tr>
+ <th>Line</th>
+ <th>Directive</th>
+ <th>Reason</th>
+ </tr>
+ </thead>
+ <tbody>
+ {unsupported.map((item) => (
+ <tr key={`${item.line}-${item.directive}`}>
+ <td>{item.line}</td>
+ <td><code>{item.directive}</code></td>
+ <td>{item.reason}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ </Modal>
+ </>
+ );
+}
diff --git a/frontend/src/pages/ImportWizard.jsx b/frontend/src/pages/ImportWizard.jsx
index 4552866e..a0440dcb 100644
--- a/frontend/src/pages/ImportWizard.jsx
+++ b/frontend/src/pages/ImportWizard.jsx
@@ -6,6 +6,7 @@ import {
Upload, Users,
} from 'lucide-react';
import api from '../services/api';
+import HtaccessConverter from '../components/apps/HtaccessConverter';
import { useToast } from '../contexts/ToastContext';
import { useConfirm } from '../hooks/useConfirm';
import { PageTopbar, Pill } from '@/components/ds';
@@ -370,10 +371,16 @@ function ImportWizard() {
icon={<ArrowDownToLine size={18} />}
title="Import a site"
meta="Bring a site over from another control panel"
- actions={step > 1 && (
- <Button variant="outline" size="sm" onClick={resetWizard}>
- Start over
- </Button>
+ actions={(
+ <>
+ {/* Imported sites often carry .htaccess rules — offer the translator here. */}
+ <HtaccessConverter />
+ {step > 1 && (
+ <Button variant="outline" size="sm" onClick={resetWizard}>
+ Start over
+ </Button>
+ )}
+ </>
)}
/>
diff --git a/frontend/src/services/api/htaccessTools.js b/frontend/src/services/api/htaccessTools.js
new file mode 100644
index 00000000..25af607b
--- /dev/null
+++ b/frontend/src/services/api/htaccessTools.js
@@ -0,0 +1,11 @@
+// .htaccess -> nginx converter (/api/v1/apps/htaccess-convert).
+// Pure text transform: paste Apache .htaccess rules, get nginx directives
+// suitable for the per-site custom nginx rules box, plus notes and a list
+// of directives that could not be translated.
+
+export async function convertHtaccess(htaccessText) {
+ return this.request('/apps/htaccess-convert', {
+ method: 'POST',
+ body: { htaccess: htaccessText },
+ });
+}
diff --git a/frontend/src/styles/components/_htaccess-converter.scss b/frontend/src/styles/components/_htaccess-converter.scss
new file mode 100644
index 00000000..35963b72
--- /dev/null
+++ b/frontend/src/styles/components/_htaccess-converter.scss
@@ -0,0 +1,150 @@
+// ============================================
+// .HTACCESS -> NGINX CONVERTER
+// Paste-in modal next to the per-site custom nginx rules editor.
+// Rendered by components/apps/HtaccessConverter.jsx.
+// ============================================
+
+.htaccess-converter {
+ display: flex;
+ flex-direction: column;
+ gap: $space-3;
+
+ &__hint {
+ margin: 0;
+ font-size: $font-size-sm;
+ color: $text-secondary;
+ line-height: 1.5;
+
+ code {
+ font-family: $font-mono;
+ color: $text-primary;
+ }
+ }
+
+ &__input {
+ font-family: $font-mono;
+ font-size: $font-size-sm;
+ resize: vertical;
+ }
+
+ &__actions {
+ display: flex;
+ justify-content: flex-end;
+ }
+
+ &__footer {
+ display: flex;
+ justify-content: flex-end;
+ gap: $space-2;
+ }
+
+ &__result {
+ display: flex;
+ flex-direction: column;
+ gap: $space-3;
+ }
+
+ &__pane {
+ background: $bg-secondary;
+ border: 1px solid $border-subtle;
+ border-radius: $radius-md;
+ overflow: hidden;
+
+ &--warn {
+ border-color: $warning-border;
+ }
+ }
+
+ &__pane-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: $space-2;
+ padding: $space-2 $space-3;
+ border-bottom: 1px solid $border-subtle;
+ font-size: $font-size-sm;
+ font-weight: 600;
+ color: $text-secondary;
+
+ svg {
+ color: $warning;
+ flex-shrink: 0;
+ }
+
+ span {
+ flex: 1;
+ }
+ }
+
+ &__output {
+ margin: 0;
+ padding: $space-3;
+ max-height: 260px;
+ overflow: auto;
+ font-family: $font-mono;
+ font-size: $font-size-sm;
+ line-height: 1.55;
+ color: $text-primary;
+ white-space: pre;
+ }
+
+ &__empty {
+ margin: 0;
+ padding: $space-3;
+ font-size: $font-size-sm;
+ color: $text-tertiary;
+ }
+
+ &__notes {
+ margin: 0;
+ padding: $space-3 $space-3 $space-3 $space-5;
+ display: flex;
+ flex-direction: column;
+ gap: $space-1;
+ font-size: $font-size-sm;
+ color: $text-secondary;
+ line-height: 1.5;
+ }
+
+ &__table-wrap {
+ max-height: 220px;
+ overflow: auto;
+ }
+
+ &__table {
+ width: 100%;
+ border-collapse: collapse;
+ font-size: $font-size-sm;
+
+ th,
+ td {
+ padding: $space-2 $space-3;
+ text-align: left;
+ vertical-align: top;
+ border-bottom: 1px solid $border-subtle;
+ }
+
+ th {
+ position: sticky;
+ top: 0;
+ background: $bg-secondary;
+ color: $text-tertiary;
+ font-weight: 600;
+ }
+
+ tr:last-child td {
+ border-bottom: none;
+ }
+
+ code {
+ font-family: $font-mono;
+ word-break: break-all;
+ color: $text-primary;
+ }
+
+ td:first-child {
+ white-space: nowrap;
+ color: $text-tertiary;
+ }
+ }
+}