diff --git a/.gitignore b/.gitignore index 8a30d25..1b75002 100644 --- a/.gitignore +++ b/.gitignore @@ -378,7 +378,6 @@ FodyWeavers.xsd # VS Code files for those working on multiple tools .vscode/* -!.vscode/settings.json !.vscode/tasks.json !.vscode/launch.json !.vscode/extensions.json diff --git a/src/BitBadger.AspNetCore.CanonicalDomains/BitBadger.AspNetCore.CanonicalDomains.csproj b/src/BitBadger.AspNetCore.CanonicalDomains/BitBadger.AspNetCore.CanonicalDomains.csproj new file mode 100644 index 0000000..70c76c3 --- /dev/null +++ b/src/BitBadger.AspNetCore.CanonicalDomains/BitBadger.AspNetCore.CanonicalDomains.csproj @@ -0,0 +1,33 @@ + + + + net6.0;net7.0 + enable + enable + 1.0.0 + Initial release + danieljsummers + Bit Badger Solutions + ASP.NET Core middleware to enforce canonical domains + icon.png + README.md + https://bitbadger.solutions/open-source/canonical-domain-middleware/ + false + https://github.com/bit-badger/BitBadger.AspNetCore.CanonicalDomains + Git + MIT License + MIT + aspnetcore middleware canonical + + + + + + + + + + + + + diff --git a/src/BitBadger.AspNetCore.CanonicalDomains/CanonicalDomainMiddleware.cs b/src/BitBadger.AspNetCore.CanonicalDomains/CanonicalDomainMiddleware.cs new file mode 100644 index 0000000..853e8aa --- /dev/null +++ b/src/BitBadger.AspNetCore.CanonicalDomains/CanonicalDomainMiddleware.cs @@ -0,0 +1,43 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Extensions; + +namespace BitBadger.AspNetCore.CanonicalDomains; + +/// +/// Middleware to enforce canonical domains +/// +public class CanonicalDomainMiddleware +{ + /// + /// The domains which should be redirected + /// + internal static readonly IDictionary CanonicalDomains = new Dictionary(); + + /// + /// The next middleware in the pipeline to be executed + /// + private readonly RequestDelegate _next; + + /// + /// Constructor + /// + /// The next middleware in the pipeline to be exectued + public CanonicalDomainMiddleware(RequestDelegate next) + { + _next = next; + } + + public async Task InvokeAsync(HttpContext ctx) + { + if (CanonicalDomains.ContainsKey(ctx.Request.Host.Host)) + { + UriBuilder uri = new(ctx.Request.GetDisplayUrl()); + uri.Host = CanonicalDomains[ctx.Request.Host.Host]; + ctx.Response.Redirect(uri.Uri.ToString(), permanent: true); + } + else + { + await _next.Invoke(ctx); + } + } +} diff --git a/src/BitBadger.AspNetCore.CanonicalDomains/IApplicationBuilderExtensions.cs b/src/BitBadger.AspNetCore.CanonicalDomains/IApplicationBuilderExtensions.cs new file mode 100644 index 0000000..cf43cc0 --- /dev/null +++ b/src/BitBadger.AspNetCore.CanonicalDomains/IApplicationBuilderExtensions.cs @@ -0,0 +1,68 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.Configuration; +using Microsoft.Extensions.Logging; + +namespace BitBadger.AspNetCore.CanonicalDomains; + +/// +/// Extensions on the interface +/// +public static class IApplicationBuilderExtensions +{ + /// + /// Initialize and use the canonical domain middleware + /// + public static IApplicationBuilder UseCanonicalDomains(this IApplicationBuilder app) + { + ParseConfiguration(GetService(app)!.GetSection("CanonicalDomains")); + + if (CanonicalDomainMiddleware.CanonicalDomains.Count > 0) + { + return app.UseMiddleware(); + } + + WarnForMissingConfig(app); + return app; + } + + /// + /// Shorthand for retrieving typed services from the application's service provider + /// + /// The application builder + /// The requested service, or null if it was not able to be found + private static T? GetService(IApplicationBuilder app) => + (T?)app.ApplicationServices.GetService(typeof(T)); + + /// + /// Extract the from/to domain paris from the configuration + /// + /// The CanonicalDomains configuration section + private static void ParseConfiguration(IConfigurationSection? section) + { + if (section is not null) + { + foreach (var item in section.GetChildren()) + { + var nonCanonical = item["From"]; + var canonical = item["To"]; + if (nonCanonical is not null && canonical is not null) + { + CanonicalDomainMiddleware.CanonicalDomains.Add(nonCanonical, canonical); + } + } + } + } + + /// + /// Generate a warning if no configured domains were found + /// + /// The application builder + private static void WarnForMissingConfig(IApplicationBuilder app) + { + var logger = GetService>(app); + if (logger is not null) + { + logger.LogWarning("No canonical domain configuration was found; no domains will be redirected"); + } + } +} diff --git a/src/BitBadger.AspNetCore.CanonicalDomains/README.md b/src/BitBadger.AspNetCore.CanonicalDomains/README.md new file mode 100644 index 0000000..483e85c --- /dev/null +++ b/src/BitBadger.AspNetCore.CanonicalDomains/README.md @@ -0,0 +1,36 @@ +## BitBadger.AspNetCore.CanonicalDomains + +This package provides ASP.NET Core middleware to enforce [canonical domains](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/Choosing_between_www_and_non-www_URLs). + +### What It Does + +Having multiple domain names pointing to the same content can lead to inconsistency and diluted search rankings. This middleware intercepts known alternate domains and redirects requests to the canonical domain, ensuring uniformity and unified search rankings. + +_If the ASP.NET Core application is running behind a reverse proxy (Nginx, Apache, IIS, etc.), enforcing these domains at that point is the most efficient. This middleware is designed for scenarios where the application is being served directly or in a container, with multiple domains pointed at the running application._ + +### How to Use + +First, install this package. + +Second, add the configuration for each domain that needs to be redirected; this middleware will configure itself via the details in the `CanonicalDomains` configuration key. An example: + +```json +{ + "CanonicalDomains": [ + { + "From": "www.example.com", + "To": "example.com" + }, + { + "From": "web.example.com", + "To": "example.com" + } + ] +} +``` + +Finally, in your main source file (`Program.cs`, `App.fs`, etc.), import the namespace `BitBadger.AspNetCore.CanonicalDomains`, and call `.UseCanonicalDomains()` on the `IApplicationBuilder` instance. It should be placed after `.UseForwardedHeaders()`, if that is used, but should be ahead of `.UseStaticFiles()`, auth config, endpoints, etc. It should be run as close to the start of the pipeline as possible, as no other processing should take place until the request is made on the canonical domain. + +### Troubleshooting + +This middleware will not throw errors if it cannot parse its configuration properly _(feel free to do the final step before adding configuration to verify!)_. However, if `.UseCanonicalDomains()` is called, and the setup does not find anything to do, it will emit a warning in the log, and will not add the middleware to the pipeline. If redirection is not occurring as you suspect it should, check the top of the log when the application starts. diff --git a/src/BitBadger.AspNetCore.CanonicalDomains/icon.png b/src/BitBadger.AspNetCore.CanonicalDomains/icon.png new file mode 100644 index 0000000..da6be2a Binary files /dev/null and b/src/BitBadger.AspNetCore.CanonicalDomains/icon.png differ