单仓库部署双域名:api域名robots.txt与访问限制规则咨询
Got it, let's tackle your requirement of running both domain.com and api.domain.com from a single codebase with the specific .htaccess rules you need. Here's the refined configuration that meets both your needs, plus clear explanations of how each part works:
Key Requirements Addressed
- Custom robots.txt for api.domain.com: We'll add a rule to serve a dedicated robots file for the API subdomain
- Restrict api.domain.com to only /api/ paths: Block all non-/api/ requests to the API subdomain with a 403 Forbidden response
Final .htaccess Configuration
# Turn on URL rewriting RewriteEngine On # Installation directory RewriteBase / # Redirect /f/ to /assets/ (existing redirect) Redirect "/f/" "/assets/" # Protect hidden files from being viewed <Files .*> Order Deny,Allow Deny From All </Files> # 1. Serve custom robots.txt for api.domain.com RewriteCond %{HTTP_HOST} =api.domain.com RewriteRule ^robots.txt$ robots-api.txt [L] # 2. Restrict api.domain.com to only /api/ paths (block all others) RewriteCond %{HTTP_HOST} =api.domain.com RewriteRule !^api/ [F,NC] # Handle missing image files by routing to custom image404 handler RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f RewriteRule \.(gif|jpe?g|png|bmp)$ index.php/image404/index/?r=%{REQUEST_URI} [NC,L] # Protect application and system files from direct access RewriteRule ^(?:application|modules|system)\b.* index.php/$0 [L] # Allow existing files/directories to be served directly RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d # Rewrite all other URLs to index.php (front controller pattern) RewriteRule .* index.php/$0 [PT]
Breakdown of Key Rules
Custom robots.txt for API subdomain:
This rule checks if the request is coming toapi.domain.comand targets therobots.txtpath. It will serverobots-api.txtinstead—just create this file in your root directory with the crawl rules specific to your API (like disallowing all crawlers if needed).Restrict API subdomain to /api/ paths:
The condition targetsapi.domain.com, then the rule uses!^api/to match any path that doesn't start with/api/. The[F]flag returns a 403 Forbidden response, blocking access to non-/api/ paths. The[NC]flag makes the match case-insensitive (so/API/or/Api/will also be allowed).Other standard protections:
- Hidden files (starting with
.) are blocked to prevent exposure of sensitive files like.envor.git - Missing image files are routed to your custom
image404handler instead of returning a generic 404 - Application/system directories are protected by routing direct requests to your front controller (
index.php) - The final rules implement the front controller pattern, routing all non-existent files/directories to
index.phpfor your application to handle routing internally
- Hidden files (starting with
内容的提问来源于stack exchange,提问作者bato3

