Initial commit
This commit is contained in:
commit
4d368488ba
12 changed files with 7287 additions and 0 deletions
25
.gitignore
vendored
Normal file
25
.gitignore
vendored
Normal file
|
@ -0,0 +1,25 @@
|
|||
# build output
|
||||
dist/
|
||||
# generated types
|
||||
.astro/
|
||||
|
||||
# dependencies
|
||||
node_modules/
|
||||
|
||||
# logs
|
||||
*.log
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
|
||||
# environment variables
|
||||
.env
|
||||
.env.production
|
||||
|
||||
# macOS-specific files
|
||||
.DS_Store
|
||||
|
||||
# local project settings
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
!.vscode/settings.json
|
9
.prettierrc.mjs
Normal file
9
.prettierrc.mjs
Normal file
|
@ -0,0 +1,9 @@
|
|||
/** @type {import("prettier").Config} */
|
||||
export default {
|
||||
trailingComma: "all",
|
||||
tabWidth: 2,
|
||||
semi: true,
|
||||
singleQuote: false,
|
||||
printWidth: 120,
|
||||
bracketSpacing: true,
|
||||
};
|
3
.vscode/extensions.json
vendored
Normal file
3
.vscode/extensions.json
vendored
Normal file
|
@ -0,0 +1,3 @@
|
|||
{
|
||||
"recommendations": ["astro-build.astro-vscode", "esbenp.prettier-vscode"]
|
||||
}
|
10
.vscode/settings.json
vendored
Normal file
10
.vscode/settings.json
vendored
Normal file
|
@ -0,0 +1,10 @@
|
|||
{
|
||||
"[javascript]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
},
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
},
|
||||
"prettier.configPath": ".prettierrc.mjs",
|
||||
"editor.defaultFormatter": "esbenp.prettier-vscode"
|
||||
}
|
7
LICENSE
Normal file
7
LICENSE
Normal file
|
@ -0,0 +1,7 @@
|
|||
© Copyright 2024 Bad Manners
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
93
README.md
Normal file
93
README.md
Normal file
|
@ -0,0 +1,93 @@
|
|||
# astro-htaccess
|
||||
|
||||
SSG-only integration for Astro 4+ to generate an Apache `.htaccess` file, from user-defined rules and Astro's configuration.
|
||||
|
||||
## Installation
|
||||
|
||||
To automatically install the integration with the default configuration:
|
||||
|
||||
```sh
|
||||
astro add astro-htaccess
|
||||
```
|
||||
|
||||
Or to install it manually, first run:
|
||||
|
||||
```sh
|
||||
npm install --save astro-htaccess@latest
|
||||
```
|
||||
|
||||
Then add it to your astro configuration (i.e. `astro.config.mjs`):
|
||||
|
||||
```diff
|
||||
import { defineConfig } from 'astro/config';
|
||||
+import htaccessIntegration from "astro-htaccess";
|
||||
|
||||
export default defineConfig({
|
||||
- integrations: [],
|
||||
+ integrations: [htaccessIntegration()],
|
||||
})
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
||||
The following properties can be passed to an object when calling `htaccessIntegration()`:
|
||||
|
||||
| Option | Description |
|
||||
| ---------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `generateHtaccessFile` | a boolean, or function that returns a boolean or a `Promise<boolean>`. If false, then no files will not be generated; if true or omitted, then `.htaccess` will be created at the root of the output directory. |
|
||||
| `errorPages` | List of custom error pages to generate for user-specified HTTP errors. If omitted, `astro-htaccess` will generate these for you based on any `src/content/*.astro` routes that match a valid HTTP error. |
|
||||
| `redirects` | List of custom redirects to add as [`RedirectMatch` rules](https://httpd.apache.org/docs/2.2/mod/mod_alias.html#redirectmatch), on top of the redirects defined in the `redirects` property of your Astro config. You can use Javascript regular expressions as the matcher, or a plain string for finer control over the output expression; and you can specify a custom redirect code for each rule (default is 301). |
|
||||
| `customRules` | Custom rules to add to the output `.htaccess` file directly. |
|
||||
|
||||
### Example configuration
|
||||
|
||||
Here, we are using an [environment variable](https://docs.astro.build/en/guides/environment-variables/) with Astro's [experimental `astro:env` API](https://docs.astro.build/en/reference/configuration-reference/#experimentalenv) to decide whether to generate our configuration file. We use a custom error in `src/content/errors/404.astro` (but we could've simply placed it at `src/content/404.astro` and removed the `errorPages` field to automatically detect it). Then, we specify two outward-bound redirects on top of Astro's redirect, and finally, we add some custom rules to enforce HTTP authentication for the whole site.
|
||||
|
||||
```js
|
||||
import { defineConfig, envField } from "astro/config";
|
||||
import htaccessIntegration from "astro-htaccess";
|
||||
|
||||
// https://astro.build/config
|
||||
export default defineConfig({
|
||||
site: "https://example.astro.build/",
|
||||
integrations: [
|
||||
htaccessIntegration({
|
||||
generateHtaccessFile: import.meta.env.GENERATE_HTACCESS_FILE === "true",
|
||||
errorPages: [{ code: 404, document: "/errors/404" }],
|
||||
redirects: [
|
||||
{ match: /^\/package@npm$/, url: "https://www.npmjs.com/package/astro-htaccess" },
|
||||
{ match: "^/github\\b", url: "https://github.com/BadMannersXYZ/astro-htaccess", code: 302 },
|
||||
],
|
||||
customRules: [
|
||||
`AuthType Basic`,
|
||||
`AuthName "Protected website"`,
|
||||
`AuthUserFile ../private/.htpasswd`,
|
||||
`require valid-user`,
|
||||
],
|
||||
}),
|
||||
],
|
||||
redirects: {
|
||||
"/faq": "/about_this_project",
|
||||
},
|
||||
experimental: {
|
||||
env: {
|
||||
schema: {
|
||||
GENERATE_HTACCESS_FILE: envField.boolean({ context: "server", access: "private", default: false }),
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
```
|
||||
|
||||
In this example, when the `GENERATE_HTACCESS_FILE` environment variable is true, a `.htaccess` file containing the following rules is generated to our output directory:
|
||||
|
||||
```txt
|
||||
AuthType Basic
|
||||
AuthName "Protected website"
|
||||
AuthUserFile ../private/.htpasswd
|
||||
require valid-user
|
||||
ErrorDocument 404 /errors/404.html
|
||||
RedirectMatch 301 ^/faq(/(index.html)?)?$ /about_this_project
|
||||
RedirectMatch 301 ^/package@npm$ https://www.npmjs.com/package/astro-htaccess
|
||||
RedirectMatch 302 ^/github\b https://github.com/BadMannersXYZ/astro-htaccess
|
||||
```
|
6896
package-lock.json
generated
Normal file
6896
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load diff
44
package.json
Normal file
44
package.json
Normal file
|
@ -0,0 +1,44 @@
|
|||
{
|
||||
"name": "astro-htaccess",
|
||||
"version": "0.0.0",
|
||||
"description": "Astro integration to generate an Apache .htaccess file",
|
||||
"type": "module",
|
||||
"exports": {
|
||||
".": "./dist/index.js"
|
||||
},
|
||||
"types": "./dist/index.d.ts",
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"check": "astro check",
|
||||
"prettier": "prettier --write .",
|
||||
"prepack": "tsc"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/BadMannersXYZ/astro-htaccess.git"
|
||||
},
|
||||
"homepage": "https://github.com/BadMannersXYZ/astro-htaccess",
|
||||
"keywords": [
|
||||
"astro",
|
||||
"astro-integration",
|
||||
"with-astro",
|
||||
"apache",
|
||||
"apache-config",
|
||||
"config",
|
||||
"htaccess"
|
||||
],
|
||||
"author": "Bad Manners <npm@badmanners.xyz>",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"astro": "^4.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@astrojs/check": "^0.9.3",
|
||||
"@types/node": "^22.5.1",
|
||||
"astro": "^4.15.1",
|
||||
"typescript": "^5.5.4"
|
||||
}
|
||||
}
|
1
src/env.d.ts
vendored
Normal file
1
src/env.d.ts
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
/// <reference path="../.astro/types.d.ts" />
|
181
src/htaccess.ts
Normal file
181
src/htaccess.ts
Normal file
|
@ -0,0 +1,181 @@
|
|||
import type { AstroIntegration } from "astro";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path, { posix as pathPosix } from "node:path";
|
||||
import { fileURLToPath, URL } from "node:url";
|
||||
|
||||
export type RedirectCode = "permanent" | 301 | "temp" | 302 | "seeother" | 303 | "gone" | 410;
|
||||
export type ErrorCode =
|
||||
| 400
|
||||
| 401
|
||||
| 402
|
||||
| 403
|
||||
| 404
|
||||
| 405
|
||||
| 406
|
||||
| 410
|
||||
| 412
|
||||
| 415
|
||||
| 418
|
||||
| 420
|
||||
| 422
|
||||
| 426
|
||||
| 429
|
||||
| 451
|
||||
| 500
|
||||
| 501
|
||||
| 502
|
||||
| 503
|
||||
| 504
|
||||
| 505;
|
||||
|
||||
export interface Config {
|
||||
generateHtaccessFile?: boolean | (() => boolean) | (() => Promise<boolean>);
|
||||
errorPages?: { code: ErrorCode; document: string }[];
|
||||
redirects?: { code?: RedirectCode; match: string | RegExp; url: string }[];
|
||||
customRules?: string[];
|
||||
}
|
||||
|
||||
const errorPageRegex = /^\/([345]\d\d)$/;
|
||||
const spaceInCharacterMatchingRegex = /([^\\]|^)\[((?:\\\]|[^ ])*) ((?:\\\]|[^ ])*)\]/g;
|
||||
|
||||
export const integration = ({ generateHtaccessFile, errorPages, redirects, customRules }: Config = {}) => {
|
||||
let assetsDir: string | null = null;
|
||||
let enabled: boolean | null = true;
|
||||
const integration: AstroIntegration = {
|
||||
name: "htaccess",
|
||||
hooks: {
|
||||
"astro:config:setup": async ({ config, logger }) => {
|
||||
if (enabled === null) {
|
||||
enabled =
|
||||
generateHtaccessFile === undefined
|
||||
? true
|
||||
: typeof generateHtaccessFile === "function"
|
||||
? !(await generateHtaccessFile())
|
||||
: !generateHtaccessFile;
|
||||
}
|
||||
if (!enabled) {
|
||||
logger.debug("generateHtaccessFile evaluated to false; skipping integration config.");
|
||||
return;
|
||||
}
|
||||
if (config.output === "server") {
|
||||
logger.warn("Cannot generate .htaccess file in SSR mode.");
|
||||
return;
|
||||
}
|
||||
if (config.adapter?.name.startsWith("@astrojs/vercel")) {
|
||||
assetsDir = fileURLToPath(new URL(".vercel/output/static/", config.root));
|
||||
} else if (config.adapter?.name === "@astrojs/cloudflare") {
|
||||
assetsDir = fileURLToPath(new URL(config.base?.replace(/^\//, ""), config.outDir));
|
||||
} else if (config.adapter?.name === "@astrojs/node" && config.output === "hybrid") {
|
||||
assetsDir = fileURLToPath(config.build.client!);
|
||||
} else {
|
||||
assetsDir = fileURLToPath(config.outDir);
|
||||
}
|
||||
},
|
||||
"astro:build:done": async ({ logger, routes }) => {
|
||||
if (enabled === null) {
|
||||
enabled =
|
||||
generateHtaccessFile === undefined
|
||||
? true
|
||||
: typeof generateHtaccessFile === "function"
|
||||
? !(await generateHtaccessFile())
|
||||
: !generateHtaccessFile;
|
||||
}
|
||||
if (!enabled) {
|
||||
logger.debug("generateHtaccessFile evaluated to false; skipping .htaccess generation.");
|
||||
return;
|
||||
}
|
||||
if (!assetsDir) {
|
||||
logger.warn("Cannot generate .htaccess file in SSR mode.");
|
||||
return;
|
||||
}
|
||||
const handledErrorCodes = new Set<number>();
|
||||
let error = false;
|
||||
const htaccess = [
|
||||
// Custom rules
|
||||
() => customRules ?? [],
|
||||
// User-defined error pages
|
||||
() =>
|
||||
!error && errorPages
|
||||
? errorPages.map(({ code, document }) => {
|
||||
if (error) {
|
||||
return "";
|
||||
}
|
||||
// Generate error pages from user input
|
||||
if (code in handledErrorCodes) {
|
||||
logger.error(`Duplicated error code ${code} detected!`);
|
||||
error = true;
|
||||
return "";
|
||||
}
|
||||
handledErrorCodes.add(code);
|
||||
return `ErrorDocument ${code} ${pathPosix.join("/", document.endsWith(".html") ? document : `${document}.html`)}`;
|
||||
})
|
||||
: [],
|
||||
// Automatic error pages and Astro redirects
|
||||
() =>
|
||||
(!error &&
|
||||
routes.reduce((acc, { type, route, redirectRoute }) => {
|
||||
if (!error) {
|
||||
switch (type) {
|
||||
case "redirect":
|
||||
acc.push(`RedirectMatch 301 ^${route}(/(index.html)?)?$ ${redirectRoute!.route}`);
|
||||
break;
|
||||
case "page":
|
||||
if (errorPages === undefined) {
|
||||
// Find error pages programtically by matching on their routes (eg. `/404`)
|
||||
const match = route.match(errorPageRegex);
|
||||
if (match && match[1]) {
|
||||
const code = parseInt(match[1]);
|
||||
if (code in handledErrorCodes) {
|
||||
logger.error(`Duplicated error code ${code} detected!`);
|
||||
error = true;
|
||||
return acc;
|
||||
}
|
||||
handledErrorCodes.add(code);
|
||||
acc.push(`ErrorDocument ${code} ${route.endsWith(".html") ? route : `${route}.html`}`);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return acc;
|
||||
}, [] as string[])) ||
|
||||
[],
|
||||
// User-defined redirects
|
||||
() =>
|
||||
!error && redirects
|
||||
? redirects.map(({ code, match, url }) => {
|
||||
if (error) {
|
||||
return "";
|
||||
}
|
||||
if (typeof match !== "string") {
|
||||
match = match
|
||||
.toString()
|
||||
// Remove slashes around regex
|
||||
.slice(1, -1)
|
||||
// Remove escaping for forward slashes
|
||||
.replaceAll("\\/", "/")
|
||||
// Replace spaces in [ ] expressions with equivalent for escaped space (%20)
|
||||
.replaceAll(spaceInCharacterMatchingRegex, "$1(?:[$2$3]|%20)")
|
||||
// Replace spaces anywhere else with escaped spaces (%20)
|
||||
.replaceAll(" ", "%20");
|
||||
if (match.search("\n") > -1) {
|
||||
logger.error(`Invalid line break in regex for ${url}`);
|
||||
error = true;
|
||||
return "";
|
||||
}
|
||||
}
|
||||
return `RedirectMatch ${code ?? 301} ${match} ${url}`;
|
||||
})
|
||||
: [],
|
||||
]
|
||||
.map((fn) => fn())
|
||||
.flat();
|
||||
if (!error) {
|
||||
await writeFile(path.join(assetsDir, ".htaccess"), htaccess.join("\n"));
|
||||
logger.info(`Generated .htaccess with ${htaccess.length} ${htaccess.length === 1 ? "rule" : "rules"}`);
|
||||
}
|
||||
},
|
||||
},
|
||||
};
|
||||
return integration;
|
||||
};
|
4
src/index.ts
Normal file
4
src/index.ts
Normal file
|
@ -0,0 +1,4 @@
|
|||
import { integration as htaccessIntegration } from "./htaccess";
|
||||
export type { Config as HtaccessConfig, RedirectCode, ErrorCode } from "./htaccess";
|
||||
export { htaccessIntegration };
|
||||
export default htaccessIntegration;
|
14
tsconfig.json
Normal file
14
tsconfig.json
Normal file
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"extends": "astro/tsconfigs/strictest",
|
||||
"compilerOptions": {
|
||||
"outDir": "./dist",
|
||||
"target": "ES2022",
|
||||
"declaration": true,
|
||||
"stripInternal": true,
|
||||
"skipLibCheck": true,
|
||||
"esModuleInterop": true,
|
||||
"noEmit": false,
|
||||
"allowImportingTsExtensions": false
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
Loading…
Reference in a new issue