12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- using System;
- using System.Windows.Forms;
- using Microsoft.Web.Administration;
- namespace IISRedirectToHTTPS
- {
- public partial class IISRedirectToHTTPS : Form
- {
- private const string RULE_NAME = "Redirect to HTTPS";
- public IISRedirectToHTTPS()
- {
- InitializeComponent();
- foreach (Site site in new ServerManager().Sites)
- {
- cb_Site.Items.Add(site.Name);
- }
- cb_Site.SelectedIndex = 0;
- }
- private void btn_Registry_Click(object sender, EventArgs e)
- {
- // IIS 서버 관리자 객체 생성
- ServerManager serverManager = new ServerManager();
- // 대상 사이트 가져오기
- Site site = serverManager.Sites[cb_Site.SelectedItem.ToString()];
- // 사이트의 재작성 섹션 가져오기
- Configuration config = site.GetWebConfiguration();
- ConfigurationSection rewriteSection = config.GetSection("system.webServer/rewrite/rules");
- // 새 규칙 생성
- ConfigurationElementCollection rulesCollection = rewriteSection.GetCollection();
- if (ExistRule(rulesCollection))
- {
- MessageBox.Show("이미 URL 재작성 규칙이 존재합니다.");
- return;
- }
- else
- {
- // 규칙을 규칙 컬렉션에 추가
- rulesCollection.Add(CreateNewRule(rulesCollection));
- // 변경 사항 저장
- serverManager.CommitChanges();
- MessageBox.Show("URL 재작성 규칙이 추가되었습니다.");
- }
- }
- private bool ExistRule(ConfigurationElementCollection rulesCollection)
- {
- foreach (ConfigurationElement existingRule in rulesCollection)
- {
- if (existingRule["name"].ToString() == RULE_NAME)
- return true;
- }
- return false;
- }
- private ConfigurationElement CreateNewRule(ConfigurationElementCollection rulesCollection)
- {
- ConfigurationElement rule = rulesCollection.CreateElement("rule");
- rule["name"] = RULE_NAME;
- rule["patternSyntax"] = "ECMAScript";
- rule["stopProcessing"] = true;
- // 일치 조건 설정
- ConfigurationElement match = rule.GetChildElement("match");
- match["url"] = "(.*)";
- // 조건 그룹 설정
- ConfigurationElement conditions = rule.GetChildElement("conditions");
- conditions["logicalGrouping"] = "MatchAll";
- conditions["trackAllCaptures"] = false;
- // 조건 추가
- ConfigurationElementCollection conditionsCollection = conditions.GetCollection();
- ConfigurationElement condition = conditionsCollection.CreateElement("add");
- condition["input"] = "{HTTPS}";
- condition["pattern"] = "^OFF$";
- condition["ignoreCase"] = true; // 대/소문자 무시
- conditionsCollection.Add(condition);
- // 동작 설정
- ConfigurationElement action = rule.GetChildElement("action");
- action["type"] = "Redirect";
- action["url"] = $"https://{"{SERVER_NAME}"}:{nud_HttpsPort.Value}/{"{R:1}"}";
- action["appendQueryString"] = true;
- action["redirectType"] = "SeeOther";
- return rule;
- }
- }
- }
|